DEV Community

Chris Cook
Chris Cook

Posted on

Match Nodes with One or More Labels

Suppose we want to find all nodes that have at least one label out of several given labels.

Find any nodes that have the label Person or Movie or both.

There are two ways to achieve this in Cypher: a static where condition or a dynamic where condition.

Static Where

The required labels are embedded directly into where condition of the Cypher query.



MATCH (n) 
WHERE (n:Person OR n:Movie) 
RETURN n


Enter fullscreen mode Exit fullscreen mode

This option is quite efficient as the query only needs to perform a label scan for each label provided and then combines the two results and removes duplicate nodes, i.e. nodes with both labels. However, adding a new label requires changing the query and thus updating the code.

Query execution plan for static where condition

Query execution plan for static where condition

Dynamic Where

Instead of embedding the labels in the Cypher query, we can provide the labels as a query parameter $labels. This parameter is a string array that we pass to the Neo4j driver when executing the query.



MATCH (n) 
WHERE any(label in labels(n) WHERE label IN $labels)
RETURN n


Enter fullscreen mode Exit fullscreen mode

This option has the advantage that we do not have to change the query if the required labels change. However, the execution might be less efficient because Neo4j first searches all nodes and then applies a filtering of the labels to the result.

Query execution plan for dynamic where condition

Query execution plan for dynamic where condition

Please let me know if there are other things to consider or there are other options I am not aware of.

Latest comments (0)