David Perez
David Perez

Reputation: 488

How to improve performance in cypher query with `OR`?

My query is: match (n :l1)-[r]-(n2 :l2) where n.id=10 OR n2.id=5 return n,n2,r

I expect this to return all the elements that contains n or n2 and have the given label.

I have indexes in both n :li(id) and n2 :l2(id) but in the profile it says that it is making a NodeByLabelScan with thousands of db hits... why?

The same query with AND does use the index.

EDIT: @StefanArmbruster solution of using UNION performs way better as it does each query separately and then merges the result without hitting the db. Millions of db hits to thousands :)

Upvotes: 1

Views: 121

Answers (1)

Stefan Armbruster
Stefan Armbruster

Reputation: 39915

I guess this is a good candidate for using UNION:

MATCH (n:l1{id:10})-[r]-(n2)
RETURN n, r, n2
UNION
MATCH (n:l2{id:5})-[r]-(n2)
RETURN n, r, n2

Upvotes: 1

Related Questions