Neo4j equivalent of a sql cross join

452 views Asked by At

I have returned a list of 1000 nodes in neo4j. I want to cross this list with itself so that I can create relationships between all pairwise combinations. In sql I would simply use a cross join. Is there an equivalent function/process that would allow me to do the same in neo4j.

My first approach was to do the following:

MATCH (b:BASKET)
WITH count(b) AS GlobalBasketCount
MATCH (n:PRODUCT)-[:COLLECTIONS]-(b:BASKET)
WITH n,count(b) AS nBasketCount,GlobalBasketCount
WHERE nBasketCount > 0.001*GlobalBasketCount 

MATCH (m:PRODUCT)-[:COLLECTIONS]-(b:BASKET)
WITH m,count(b) AS mBasketCount,n,nBasketCount,GlobalBasketCount
WHERE mBasketCount > 0.001*GlobalBasketCount AND m.id < n.id

CREATE (m)-[r:RELATIONSHIP]->(n)
WITH m,n,r,nBasketCount,mBasketCount
SET r.BasketCountProduct = nBasketCount*mBasketCount

However, this requires the same product list to be created 1001 times via match queries, which is very inefficient.

Side Note: The

m.id < n.id

is to prevent duplicate pairs.

1

There are 1 answers

3
Michael Hunger On BEST ANSWER

Try this:

MATCH (n:Foo)
WITH collect(n) as nodes
UNWIND nodes as n1
UNWIND nodes as n2
WITH n1,n2
WHERE id(n1) < id(n2)
...