Counting k-hop neighborhood


#1

I can get k-hop neighborhood using this query:

test(func: uid(0x29fa)) @recurse(depth: k) {  
    uid
    expand(_all_)
}

And I know I can count unique nodes that come in JSON response manually, but is there a way to get size of neighborhood in query response?


(Michel Conrado) #2

certainly you can do it with https://docs.dgraph.io/query-language/#count


#3

Can you please point me to the right direction, because neither

{
  test(func: uid(0x29fa)) @recurse(depth: 2) {  
    uid
  	expand(_all_) {
      count(uid)
    }
 }
}

nor

{
  test(func: uid(0x29fa)) @recurse(depth: 2) {  
    count(uid)
    expand(_all_)
 }
}

gives me what I need


(Michel Conrado) #4

Please give me a sample, a context. So I can help. By your query and text, I can’t tell.


#5

Well, the context is - I know UID of the node, how can I get the size of the k-hop neighborhood (the amount of nodes connected to the provided one directly, or through other nodes, up to the k-th depth). For example here, the size of the neighborhood of this node is 13:

{
  test(func: uid(0x29fa)) @recurse (depth: 2) {  
    uid
    expand(_all_)
  }
}

image

So how can I get only that number (13 in this case) using count or any other function?


(Michel Conrado) #6

A sample also would be good. If I don’t know what its structure is like, I can’t explore the possibilities. Also, Recurse is a very different query from others, some things may not work well depending on the structure.


(Michel Conrado) #7

You may need to do:

{
  test(func: uid(0x29fa)) @recurse(depth: 2) {  
    count(httfr)
    count(httfre)
    count(<FAW Women's>)
    expand(_all_)
 }
}

#8

This looks like hardcoding (I mean those httfr, httfre and <FAW Women's>). What if predicates are unknown at the moment of the query execution?


(Michel Conrado) #9

In recursive query is mandatory to insert the predicates you need. Cuz it can traverse a lot of type of nodes. And the purpose of the recurse is for recursing in a determined set of predicates/edges. Otherwise you should just use expand_All.
e.g:

{
  test(func: uid(0x29fa)) @recurse(depth: 2) {  
    expand(_all_) {
      expand(_all_)
  }
 }
}

This way you will expand all recursively predicates to as many levels as you need. However, there is no “count(_all_)”.

PS. I believe hardcoding is important as it makes the responses predictable (Including the position of keys and values in the answer). I would never recommend using expand_all in a production application. Only if you know what you doing, if you have total control of your DB, Schema, Dataset and you’re okay with it.