What exactly is the syntax for aggregation functions like sum()?
For example, take the following structure:
let json = {
"ages": {
"age": [
"20",
"30",
"40"
]
}
}
and that
for age in json.ages.age return age
returns
["20", "30", "40"]
All of the following snippets return "[1542] invalid argument type used in call to function 'SUM()'" in Arango 2.0.4:
// LR
let ages = (for age in json.ages.age return age)
return sum(ages)
// LR
let ages = (
for age in json.ages.age
return age
)
return sum((for age in json.ages.age return age))
// R
return sum((for age in json.ages.age return age))
What is the correct syntax?
The syntax page (http://www.arangodb.org/manuals/current/Aql.html#AqlFunctionsList) does not appear to have any related examples.
The closest thing I could find to a syntax example is this: https://www.arangodb.org/foxx
controller.get("/revenue/:year", function (req, res) {
var query = "RETURN SUM((FOR bill IN billcollection FILTER bill.year == @year RETURN bill.amount))";
var stmt = db._createStatement({ "query": query});
stmt.bind("year",parseInt(req.params("year"),10));
var c = stmt.execute();
res.json(c);
});
but it seems to have the syntax above that is failing for me.
Is there a more detailed syntax reference anywhere?
Your approach is correct, however you missed a tiny spot in the docs. ;)
In the docs for SUM() it says:
SUM(list) : returns the sum of the values in list. This requires the elements in list to be numbers. null values are ignored.
(Docs reference: https://www.arangodb.org/manuals/current/Aql.html#AqlFunctionsList)
Note the "This requires the elements in list to be numbers"
So, your JSON-example should have numbers in the list, instead of strings.
let json = {
"ages": {
"age": [
20,
30,
40
]
}
}
let ages = (for age in json.ages.age return age)
return sum(ages)
Copying and running the above snippet into your AQL editor should result in the desired:
[
90
]
You can of course also leave your json intact and type-cast the strings into numbers by changing the AQL query accordingly:
let json = {
"ages": {
"age": [
"20",
"30",
"40"
]
}
}
let ages = (for age in json.ages.age return TO_NUMBER(age))
return sum(ages)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With