Hi, I have been running into this issue where I can’t seem to correctly query for the sum of the facets for multiple nodes.
For a minimal example: https://docs.dgraph.io/query-language/#facets-and-aggregation Here, instead of querying the average rating for each movie, if we wanted to simply output the sum of the ratings of each movie… I tried to run the following query:
{
var(func: has(rated)) {
rated @facets(r as rating)
total_rating as sum(r)
}
data(func: uid(total_rating)) {
name
val(total_rating)
}
}
That one is tricky. Cuz the sum func is applied to nodes(entities), not values that are between two entities. So the sum would be applied correctly (and it would assume that values in facets belong to one level, after all the query has only one level) to the first-class citizens only, when you’re doing a wide query. That’s why we have the sum of all ratings together. Cuz facets can’t simulate “first-class”.
One way to “solve” this, is to use pagination. And paginate one by one. So you can have the values you need. That’s a “hacky” way of doing it. But if you still wanna do it in the DB query that’s the way.
e.g:
{
var(func: has(~rated) , first:1, offset:0) { # offset: 0|1|2...
~rated @facets(r as rating)
total_rating as sum(val(r))
}
data(func: uid(total_rating)) {
name
val(total_rating)
}
}
As I imagine, to support this we would create a kind of “temporary emancipation of facets as first-class” (funny phrase hehe) just to apply this. I think that this could take time to be implemented. So do it on the client-side as Francesc says or in a “hacky” way.