Search code examples
neo4jcypher

Why does this Neo4j query skips a match?


If I fill an empty database with this data

CREATE (an:Person { name: "Anders" })
CREATE (ces:Person { name: "Caesar" })
CREATE (boss:Person { name: "Bossman" })
CREATE (geor:Person { name: "George" })
CREATE (dav:Person { name: "David" })
CREATE (an)-[:BLOCKS]->(ces)
CREATE (an)-[:KNOWS]->(boss)
CREATE (an)<-[:KNOWS]-(dav)
CREATE (ces)-[:KNOWS]->(geor)
CREATE (boss)-[:KNOWS]->(geor)
CREATE (boss)-[:BLOCKS]->(dav)
CREATE (dav)-[:BLOCKS]->(dav)

And then run this query

MATCH (x { name: "David" })--(y)-->(z) RETURN x.name, y.name, z.name

I get these results

╒═══════╤═════════╤═════════╕
│x.name │y.name   │z.name   │
╞═══════╪═════════╪═════════╡
│"David"│"David"  │"Anders" │
├───────┼─────────┼─────────┤
│"David"│"Bossman"│"George" │
├───────┼─────────┼─────────┤
│"David"│"Anders" │"Bossman"│
├───────┼─────────┼─────────┤
│"David"│"Anders" │"Caesar" │
└───────┴─────────┴─────────┘

The first row proves there can be duplicate nodes, so why doesn't this row get returned?

╒═══════╤═══════╤═══════╕
│x.name │y.name │z.name │
╞═══════╪═══════╪═══════╡
│"David"│"David"│"David"│
└───────┴───────┴───────┘

Solution

  • There is only one self-loop on the David node, so (David)-->(David)-->(David) would require going over the same self-loop twice. But in Cypher paths returned are not allowed to have repeated relationships (they are allowed to have repeated nodes, as you observed).