Foreach In Query itself
{
var (func: eq(name, "nodeA")) {
ED as edge
}
products(func: foreach(ED)) @normalize {
T as num
to {
i as num
product: math(T * i)
}
}
}
Result
{
"data": {
"products": [
{
"product": 3
},
{
"product": 4
},
{
"product": 6
},
{
"product": 8
}
]
}
}
Instead of
{
products(func: eq(name, "nodeA")) @normalize {
name
edge {
T as num
to {
i as num
product: math(T * i)
}
}
}
}
{
"data": {
"products": [
{
"product": 12
},
{
"product": 9
},
{
"product": 12
},
{
"product": 9
}
]
}
}
Solving Queries (facets, aggregation, maths and so on) with foreach.
Solving this issue
https://github.com/dgraph-io/dgraph/issues/4160
As you can see the partial maths get broken due some internal behavior in Dgraph’s query. To not try to change the design internally. We can add foreach to solve this.
See this query
{
Anne(func: has(rated), first: 1, offset: 0) {
name
rated @facets(r as rating)
partial_sum: sum(val(r))
}
Brian(func: has(rated), first: 1, offset: 1) {
name
rated @facets(rb as rating)
partial_sum: sum(val(rb))
}
}
With this query, I can overcome the issue related in the report.
I gonna have this result
{
"data": {
"Anne": [
{
"name": "Anne",
"rated": [
{
"rated|rating": 2
},
{
"rated|rating": 5
}
],
"partial_sum": 7
}
],
"Brian": [
{
"name": "Brian",
"rated": [
{
"rated|rating": 2
}
],
"partial_sum": 2
}
]
}
}
BUT if I use foreach, I can “simulate” this query above by doing
{
A as var(func: has(rated))
q(func: foreach(A)) {
name
rated @facets(r as rating)
partial_sum: sum(val(r))
}
}
This foreach query is basically creating two queries (cuz theres is two nodes “Anne” and “Brian”) internally and merging the results into one single result.