Aggregate Function
The aggregate function in SwartzDB is used to perform calculations on a list of numeric values. It works seamlessly with the filter function when extracting numeric data.
How aggregate Works
The aggregate function supports several operations:
| Operation | Description |
|---|---|
| SUM | Adds up all values. |
| MIN | Finds the smallest value. |
| MAX | Finds the largest value. |
| AVG | Computes the average. |
| COUNT | Counts the number of elements. |
Example Usage:
$result = $sdb->aggregate([10, 20, 30], 'SUM');
// Output: 60
Using aggregate with filter
Since filter extracts specific fields, it can return a list of numeric values. This list can then be passed directly into aggregate for calculations.
Example: Sum of All Prices
$filteredPrices = $sdb->filter($data, ["price"]);
$totalPrice = $sdb->aggregate($filteredPrices, 'SUM');
filterextracts only the"price"column.aggregatecalculates the total sum.
Example: Finding the Highest Score
$scores = $sdb->filter($data, ["score"]);
$maxScore = $sdb->aggregate($scores, 'MAX');
filterretrieves all scores.aggregatefinds the highest score.
Example: Calculating the Average Age
$ages = $sdb->filter($data, ["age"]);
$averageAge = $sdb->aggregate($ages, 'AVG');
filterextracts all ages.aggregatecomputes the average.
Why Use aggregate with filter?
✅ Dynamic calculations – Works with extracted data without needing manual processing.
✅ Efficient – Processes only relevant values instead of looping through full datasets.
✅ Readable Code – Makes operations like sum, min, and average easy to implement.
Conclusion
The combination of filter and aggregate provides a powerful way to process numerical data in SwartzDB. First, filter extracts a specific column, then aggregate performs calculations on the result.