Felix Arnold
Felix Arnold

Reputation: 891

Neo4J, Match node with "OR"

Helo,

i want to match a graph where a node can be typeX or typeY my first thought was:

match (:typeX|typeY)-[]-(z) return z

But this doesn´t work :(

Is there any way without typing the query twice? Like this:

match (:typeX)-[]-(z), (:typeY)-[]-(z) return z

Can someone help me? thank you in advance :)

Upvotes: 2

Views: 1870

Answers (4)

InverseFalcon
InverseFalcon

Reputation: 30397

Unfortunately there's not a good efficient way to do this without sacrificing performance. All other current answers are forced to scan all nodes and then filter on their labels, which isn't performant with large numbers of nodes (PROFILE the queries). All the efficient means I know of are more verbose.

You can perform a UNION of the two queries to return nodes one hop from all :typeX and :typeY nodes.

 match (:typeX)--(z)
 return z
 union
 match (:typeY)--(z)
 return z

Upvotes: 3

Michael Hunger
Michael Hunger

Reputation: 41676

there is a n predicate n:Label

MATCH (n)--(z)
WHERE n:typeX OR n:typeY
RETURN z

Upvotes: 0

cybersam
cybersam

Reputation: 66999

This query will work even if n has multiple labels:

MATCH (n)
WHERE ANY(lab IN labels(n) WHERE lab IN ['typeX', 'typeY'])
MATCH (n)--(z)
RETURN z

Upvotes: 0

Luanne
Luanne

Reputation: 19373

One way is

MATCH (n) WHERE labels(n) IN ['typeX','typeY'] 
WITH n
MATCH (n)-[]-(z)
RETURN z

However, if "either typeX or typeY" are queried frequently and share some common purpose in your domain, you could add another common label to them like "commonXY" and query using that label instead.

Upvotes: 6

Related Questions