Apply @recurse until @filter condition is met

Hi, there! I’ve wanted to test DGraph for years and finally found a good use case. I’m still prototyping the relationships I need to build, so I’ll try to be as brief as possible

What I want to do

I need to recursively find a node, which may be up to n levels of depth.
The type is basically:

type SomeType {
    value: string
    next: SomeType
}

Let’s say I have the following graph: A->B->C->D->E->F. An example would be listing all nodes from B to E (resulting in B->C->D->E), without actually knowing the depth.

What I did

Following the recurse query I’ve tried the snippet below, but the filter doesn’t apply recursively.

{
    query(func: eq(value, "C")) @recurse(loop: false) {
        value
        next @filter(eq(value, "E"))
  }
}

So, is it possible to traverse the graph recursively until the filter condition is met?

It does apply. The problem is that it will check for the first next edge object and verify that it is not eq(value, “E”) and it will stop. Remove the condition and it will continue.

There is no way to say “only If you find value X stop”. When you use eq, it will stop in the first attempt. As value, “D” is not equal to “E”.

Why not use shortest path? can you say what is the goal you wanna achieve?

Shortest path you can do

{

 C as var(func: eq(value, "C"))
 E as var(func: eq(value, "E"))

 path as shortest(from: uid(C), to: uid(E), numpaths: 2) {
  next 
 }
 path(func: uid(path)) {
   value
 }
}

1 Like

Didn’t occur to me to use the shortest path because there was actually only one path and I was blindly trying to iterate the graph as if it was a linked list. This worked like a charm!
The actual use case will be traversing and counting relationships between nodes, from a given node “A” to “B”.
Of course, the actual use case won’t be as simplistic, but for learning purposes, I’m focusing on the problem itself, which is essentially traversing a graph where all nodes will be reachable from every other node, but with different paths.
Thank you for the support :heart:

1 Like