Friends of Friends n hops away


(Stanka Dalekova) #1

Hi,

is there a way to take all nodes n hops away. For example

 {
  set {
   _:a <name> "a" .
   _:b <name> "b" .
   _:c <name> "c" .
   _:d <name> "d" .
   _:e <name> "e" .

   _:a <child> _:b .
   _:b <child> _:c .
   _:c <child> _:d .
   _:d <child> _:e .
   
   _:a <type> "astnode" .
   _:b <type> "astnode" .
   _:c <type> "astnode" .
   _:d <type> "astnode" .
   _:e <type> "astnode" .

   _:a <kind> "file" .
   _:b <kind> "class" .
   _:c <kind> "func" .
   _:d <kind> "if" .
   _:e <kind> "var" .
  }
}

For example 2 hops from c we have a and e.
How can I acheive this? Is it with a recursive query? Can you show me how?
I have gone trough some posts, for example Recursive Queries
But I cannot get a working example(recursive query does not compile), can you please help?

Thanks,
Stanka


(Pawan Rawal) #2

For two hops, you can just do this. Note, edges are not bidirectional in Dgraph so this won’t give a, only e.

{
  me(func: uid(c)) {
    child {
      child {
        name
      }
    }
  }
}

(Stanka Dalekova) #3

When I execute the upper statement I got
“Some variables are used but not defined Defined: Used:[c]”


(Pawan Rawal) #4

You have to use the unique id for c. Sorry, I didn’t make that clear. Another way is to search by name.

{
  me(func: eq(name, "c")) {
    child {
      child {
        name
      }
    }
  }
}

(Stanka Dalekova) #5

Thank you very much, this works as expected! I have tree more questions:
1)Can I get C parent easily? For example: get all c direct descendants and ascendants, i.e. can I go back?
2)Is there a special property for node type? For example if I have two types of nodes, one for movies and one for directors, how to take all movies?
3)Can I take first 10 nodes, BUT without filter


(Stanka Dalekova) #6

Should I post these questions as a separete post? Thank you, Stanka.


(Pawan Rawal) #7

All these questions could have been answered by doing a little more research as they have been asked before.

Sure, look at reverse edges.

Dgraph doesn’t assign any labels to nodes by default. you have to associate a property for the type of nodes. Then you can do a has query. See https://docs.dgraph.io/howto/#giving-nodes-a-type

You have to apply a function at root to filter the initial set of nodes. Then you can take the first 10 or first n.


(Srinath Ganesh) #8

so is there any way to ‘search’ bi-directionally?


(Adam Hopkins) #9

For anyone that ends up here looking for a similar answer, take a look at my related question here: Flattening to get unique nodes within n steps