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

139 views Asked by At

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.

1

There are 1 answers

0
Huzaifa Ahmed On

If you are looking for to avoid the cartesian product issue with the given 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

I suggest to use this one below

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

It will remove the cartesian product issue. Try this..