Cypher query for a complete path between several related nodes?

I'm drawing a blank on this one. Lets say I have the following graph:

A->B->C->D

What would be the query to return the path from A to D where A.name="Foo"? I thought I had seen an example of doing this without having to specify the intermediate nodes (which may not necessarily go out to D but could terminate a B or C in some cases).

Thanks

After a little more research, it looks like the apoc.path.expandConfig() call might be what I'm actually looking for in this case.

You can try this:

MATCH (a:Person) where a.name = "A"
CALL apoc.path.spanningTree(a,{ bfs:false, maxLevel:3}) YIELD path  
RETURN path

You can set maxLevel to your desired value. I set the bfs flag to false to go depth first.

It is a single path and not a tree that you want to get, then the following form works. It depends on your use case. I think you were referring to the variable length path search, which is shown in the query. In this case, the query will look for paths between 1 and 3 hops.

match(a:Label{name:"Foo"})
match path=(a)-[*..3]-(d)
return path
1 Like

Thanks. I will give that a try also. I've never been able to get the [*1..x] option to work in my graphs in the past so this will be interesting.

I was just poking around with this syntax this week, and it works like a champ. What wasn't working for you?

It could have been the nature of my query or the data, but I've never been able to get that syntax to work. It didn't indicate an error but no matter what values I put into that part of the relationship I kept getting the same result when I believed it would have been different (more or fewer hops depending on the value).

I have some more robust datasets lately that I haven't tried out with that option.

Keep in mind, if you have a variable length pattern starting an a given node and you have no constraint on the end node, you will get the longest path and all intermediary paths. For example, a path A->B->C->D, a variable length query anchored on A, will return:

A->B
A->B->C
A->B->C->D

If you don’t anchor on A, will will get every possible segments from A to D

Maybe this made the results unexpected.

1 Like
Do you have a graph like this?

Screen Shot 2023-06-08 at 4.42.18 PM

If yes, then you will get the same answer for any path variable.

If you have an example where it doesn't work as expected, please share it with us - we can take a look and help explain the results

This may be more of a case of my misunderstanding how to use that option. It appears you specify start & end nodes and it looks "1..x" hops in between. I think I was using it incorrectly by thinking it would expand beyond the end node specified. I'll have to give it a try later.