Get all descendents from a given parent in the graph


#1

So I’m looking at modelling a simple user referral tree where at the top level the nodes don’t have have a referer, then the next level down the node has a referer set to the parent node, which can then go down as deep as the referral tree goes. Sorry for the n00b question I’m trying to get my head around how to model this and query the data:

Schema:

<name>: string @index(term) 
<referer>: uid @count .

Data:

{
  set {
    _:steven <name> "Steven" .
    
    _:john <name> "John" .

    _:bob <name> "Bob" .
    _:bob <referer> _:steven .
    
    _:bill <name> "Bill" .
    _:bill <referer> _:bob .
  }
}

I want to know all of the child nodes for the user steven, how would I query that? Am I modelling this correctly?


(Michel Conrado) #2

You could use recursive.

{
	q(func: eq(name, "Bill")) @recurse(depth: 5, loop: true) {
		name
		referer
	}
}

https://docs.dgraph.io/query-language/#recurse-query


#3

Hey MichelDiz,

Thanks for the reply, that works well but it’s the wrong way around for me as it finds me the top level parent of “Bill” which is “Steven”, however I want to find all of the children nodes of the given node. So From “Steven” I want to find “Bob” and “Bill”.

Is there a way to do that?


(Michel Conrado) #4

So in this case you should use reverse edges.

<referer>: uid @count @reverse .
{
	q(func: eq(name, "Steven")) @recurse(depth: 5, loop: true) {
		name
		~referer
	}
}