Cartesian Product of Paths Produces Unexpected Result


I have a sample graph generated by the following command

CREATE p = (:x {name: 'a'}) -[:next]-> (:y {name: 'b'})-[:next]-> (:x {name: 'c'})-[:next]-> (:y {name: 'd'}), q = (:y {name: 'b'})-[:next]-> (:x {name: 'c'})-[:next]-> (:y {name: 'd'}), r = (:x {name: 'a'}) -[:next]-> (:y {name: 'b'})-[:next]-> (:x {name: 'c'})-[:next]-> (:y {name: 'e'}) RETURN *

For some analysis I am doing, I want a cartesian product of the paths. Just to check whether the cartesian product is working, I do

MATCH (n), (m)
RETURN id(n), id(m)

And get

id(n) id(m)
190 190
190 191
190 192
190 193
... ...

This is all as expected. Then I want to check that the cartesian product of paths is working fine and run

MATCH p = ()-[*]->(), q = ()-[*]->()
WITH nodes(p) as np, nodes(q) as nq
RETURN id(np[0]), id(nq[0])

And get

id(np[0]) id(nq[0])
190 191
190 191
190 192
190 194
190 194
190 195
... ...

This is weird. I was expecting that the starting node of the paths should be repeated at least once. It isn't repeated anywhere in the whole table of results.

It should be repeated since if we have p = q = [190->191,191->192]
Then we have p x q = [ (190->191, 190->191), (190->191, 191->192), (191->192, 190->191), (191->192, 191->192) ].

Can someone explain why this result is not present in the real query?


  • Neo4j 4.3.1 Enterprise, Desktop 1.3.11, browser 4.2.0
  • Using browser

In looking at this a bit, I tried two separate MATCH statements and get a different answer which led me to this post, which explains a bit about what is going on

but personally I agree, it feels like inconsistent behavior (unexpected, unnatural) in fact we are warned that the MATCH is a cartesian product.

"This query builds a cartesian product between disconnected patterns."

1 Like

Thank you! I was not aware one MATCH statement only traversed each path once. This is a good explanation as to why two MATCH statements are necessary to perform the cartesian product of paths.

Not sure this is a solution to the warning, but I marked it as a solution because it is helpful for explaining why the cartesian product is not performed and how to use two MATCH statements to get the desired result.