cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Cartesian Product of Paths Produces Unexpected Result

Hello,

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?

Thanks

  • Neo4j 4.3.1 Enterprise, Desktop 1.3.11, browser 4.2.0
  • Using browser
1 ACCEPTED SOLUTION

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."

View solution in original post

2 REPLIES 2

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."

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.

Nodes 2022
Nodes
NODES 2022, Neo4j Online Education Summit

All the sessions of the conference are now available online