Count all nodes in Dgraph

Is there a way of retrieving the count of all existing nodes in the graph?
I don’t need todo this often, only for sanity checks. there used to be a way using has(_predicate_) but it doesn’t work anymore.

If all nodes in your db have the dgraph.type edge, then you can do this:

query {
  count(func: has(dgraph.type)) {
    count(uid)
  }
}
2 Likes

It seems none of the nodes have been created with that edge

Hi @slawo, you need to have defined dgraph.type to the nodes. For example:

{
  set {
    _:a <name> "Becky" .
    _:a <dgraph.type> "Pet" .
  }
}

Welcome Slawo! if you don’t have types (nodes with dgraph.type) and need a reliable sanity check of whats in the db, you could export data from alpha regularly. The data is exported in rdf or json format and you can get counts from there. I know it sounds like an overkill, but it is an option that will serve the need fully.

You could use the /state endpoint to get maxLeaseId. That will give you an upper bound on the count of uids leased till now, but not the exact count. There is no other easy way than to have that dgraph.type edge.

If your schema has only a few predicates, but no / not all nodes have dgraph.type assigned, then you can do the following (here there are only three predicates in the schema:

pred1 as var(func: has(<dgraph.graphql.schema>))
pred2 as var(func: has(<dgraph.graphql.xid>))
pred3 as var(func: has(<dgraph.type>))

result (func: uid(pred1,pred2,pred3)) {
  count(uid)
}

You can retrieve the schema programaticaly and then generate this query. It works nicely with hundreds of predicates.

3 Likes