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
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.
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
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.
Please let me know if there are other things to consider or there are other options I am not aware of.
Top comments (0)