user4201983
user4201983

Reputation: 97

Neo4j path query including cycles

Let's assume we have a graph that includes this cycle:

{id:1, start:true, end:false} --> {id:2, start:false, end:true}
{id:1, start:true, end:false} <-- {id:2, start:false, end:true}

I'd like to write a query that finds all paths of a specific length from nodes with start:true to nodes with end:true, like (for length 3):

(n1 {start: true})-[:*3]-(n4 {end: true})

but the results should include cyclic paths like:

{id:1, start:true, end:false} --> {id:2, start:false, end:true} --> {id:1, start:true, end:false} --> {id:2, start:false, end:true}

Is that possible in Cypher 2.1?

Upvotes: 1

Views: 1955

Answers (1)

JohnMark13
JohnMark13

Reputation: 3739

The answer to this question is Yes, and the syntax that you have used in your example query is correct. It is correct because you have left any directional indicators out of your query meaning that traversal will occur in both forward and backward directions.

One thing I am not sure about is whether you can use start and end as property names, and if you can, whether you should as they both serve functional purpose in Cypher.

Edit - Having understood the question

I think that Cypher will not revist relationships in traversal although I cannot see any documentation about this, it would represent some odd path analysis results. I am sure you could use the traversal API to write your own traversal that could..

You can achieve what you want in Cypher, my version doesn't scale well to longer paths and I'm sure someone can do a better job than this:

MATCH (a:Thing{start:true})-[:REL]-(b:Thing)
WITH DISTINCT a, b
MATCH (b)-[:REL]-(c:Thing)
WITH DISTINCT a, b, c
MATCH (c)-[:REL]-(d:Thing{end:true})
RETURN DISTINCT a, b, c, d

Upvotes: 2

Related Questions