DEV Community

Chris Cook
Chris Cook

Posted on

2

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more