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.

“Query Optimization” : Neo4j Query builds a cartesian product between disconnected patterns -

I’m supposed to have graph of multiple nodes(more than 2) with their relationships at 1st degree, second degree, third degree.

For that right now I am using this query

WITH ["1258311979208519680","3294971891","1176078684270333952",”117607868427845”] as ids 
MATCH (n1:Target),(n2:Target) WHERE n1.id in ids and n2.id in ids and n1.id<>n2.id and n1.uid=103 and n2.uid=103 
MATCH p = ((n1)-[*..3]-(n2)) RETURN p limit 30

In which 4 nodes Id’s are mention in WITH[ ] and next [*..3] it is used to draw 3rd degree graph between the selected nodes.

WHAT the ABOVE QUERY DOING

After running the above query it will return the mutual nodes in case of second degree [*..2] if any of the 2 selected nodes have mutual relation it’ll return.

WHAT I WANT

  1. First of all I want to optimize the query, as it is taking so much time and this query causing the Cartesian product which slow down the query process.

  2. As in this above query if any 2 nodes have mutual relationship it will return the data, I WANT, the query will return mutual nodes attached with all selected nodes. Means if we have some nodes in return, these nodes must have relation to all selected target nodes.*

Any suggestions to modify the query, to optimize the query.

Stackoverflow link : https://stackoverflow.com/questions/64167019/query-optimization-neo4j-query-builds-a-cartesian-produ...

3 REPLIES 3

ameyasoft
Graph Maven
Took the result suggested in the above Stackoverflow link  and modifying it:

MATCH (node1:Target) WHERE node1.id IN ["1258311979208519680","3294971891","1176078684270333952"]
MATCH (node2:Target) WHERE node2.id IN ["1258311979208519680","3294971891","1176078684270333952"]

MATCH p=(node1)-[*..2]-(node2) 
where node1.id <> node2.id and node1.uid = 103 = node2.uid
RETURN p

This query will solve the cartesian product issue but it will return the mutual nodes if any of the two nodes have some mutual nodes.
But how can this be changed as he asked, the query should return the relationship only if it is linked with all the selected nodes (in array).
Means if we want to create the second degree graph there should be the mutual nodes which are connected with all the target nodes.

Hello @alishahaan9 and @ameyasoft

I think we can also move the last WHERE clause:

MATCH (node1:Target)
WHERE node1.id IN ["1258311979208519680","3294971891","1176078684270333952"]
MATCH (node2:Target)
WHERE node2.id IN ["1258311979208519680","3294971891","1176078684270333952"]
WITH node1, node2
WHERE node1.id <> node2.id and node1.uid = 103 = node2.uid
MATCH p=(node1)-[*..2]-(node2)
RETURN p

Regards,
Cobra