How can I get the COUNT of a certain field that suppose to return a list of connected entities?

I am not sure whether I have to make provisions in my Slash GraphQL schema or I can directly get the count irrespective of the schema.
Like in the below example, how can I get the COUNT of posts that are associated with the user.

The best way I can think of, for now, is to query all the posts and let the front-end extract the count from the length of the returned posts-list.

query MyQuery {
  getUser(email: "sourabh@gmail.com"){
    id
    email
    name
    picture
    posts {
      ***post related attributes***
    }
  }
}

Option 1: You could connect via any Dgraph client to slash as mentioned here and fire a count query. As mentioned, " The form count(uid) counts the number of UIDs matched in the enclosing block.". This will help you count the posts.

Option 2: Fire a custom DQL as mentioned here.

IMO, option 1 might be better here.

1 Like

Just be aware that counting via DQL with either option above disregards all auth directives from the graphql endpoint. You could end up with a count higher than what is actually authorized in some cases.

2 Likes

Umm thanks for pointing out, that might cause problems later on. Ideally, I think Slash-GraphQL should natively support the count feature, like with the help of some directive or config, any thoughts @amaster507? Can we raise a feature request for this?

Its in the works I do believe to some extent for the 20.11 release.

1 Like

Yes. Count Queries will be part of 20.11 release. They were pushed to master just today.
Related RFC: Count Queries in GraphQL .
The query in your case will look something like this.
We will shortly be updating the related documentation.

query MyQuery {
  getUser(email: "sourabh@gmail.com"){
    id
    email
    name
    picture
    postsAggregate{
      count // Gives you count of posts
    }
    // any other fields.
  }
}
2 Likes

I have tried the above solution @rajas, it is not working, the error says

“Cannot query field "postsAggregate" on type "User".”

Can you share details of your schema ?
Also, the related commit was pushed around an hour ago. The feature is not yet available on Slash.
Did you clone and build Dgraph on the latest master ?

I tried creating a new backend, the version of Dgraph is still 20.07 not sure why. @rajas
I have also tried using the “clone backend” method but same 20.07 is appearing.

Slash runs on a different version of Dgraph than master. The version of Dgraph which is used by Slash is periodically upgraded.
Count Queries will be available on Slash after the next version upgrade.
Next version is scheduled to happen in the coming month around the time of 20.11 release.

2 Likes