Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j: Match multiple labels (2 or more)

Tags:

neo4j

cypher

I would like to do a search, and I would like to start traversing from 2 labels (OR condition). For example, I need to find out all the nodes which have labels either 'Male' or 'Female' and whose property, name =~ '.ail.'.

like image 920
gaurav.singharoy Avatar asked Nov 15 '13 14:11

gaurav.singharoy


People also ask

Can a node have multiple labels Neo4j?

Neo4j CQL CREATE a Node Label We can say this Label name to a Relationship as "Relationship Type". We can use CQL CREATE command to create a single label to a Node or a Relationship and multiple labels to a Node. That means Neo4j supports only single Relationship Type between two nodes.

What is the syntax for getting all the nodes under specific label in Neo4j?

If you want to get the labels of a specify node, then use labels(node) ; If you only want to get all node labels in neo4j, then use this function instead: call db. labels; , never ever use this query: MATCH n RETURN DISTINCT LABELS(n) . It will do a full table scan, which is very very slow..

How many labels can a node have Neo4j?

A node can have zero to many labels. In the example graph, the node labels, Person , Actor , and Movie , are used to describe (classify) the nodes. More labels can be added to express different dimensions of the data.


1 Answers

You can put this condition in the WHERE clause:

MATCH (n) WHERE n:Male OR n:Female RETURN n 

EDIT

As @tbaum points out this performs an AllNodesScan. I wrote the answer when labels were fairly new and expected the query planner to eventually implement it with a NodeByLabelScan for each label, as it does for the single label case

MATCH (n) WHERE n:Male RETURN n 

I still think this is a reasonable expression of the query and that it is reasonable to expect the query planner to implement it with label scans, but as of Neo4j 2.2.3 the query is still implemented with an AllNodesScan and a label filter. Here is therefore a more verbose alternative. Since the label disjunction signifies a set union and this union can be expressed in different ways, we can express it in a way that the query planner implements without scanning all nodes, and instead starts with a NodeByLabelScan per label.

MATCH (n:Male) WHERE n.name =~ '.ail.' RETURN n UNION MATCH (n:Female) WHERE n.name =~ '.ail.' RETURN n 

This means expressing the query once for each label and joining them with an explicit UNION. This is not unreasonable, at least for smaller number of labels, but it's not clear to me why the query planners shouldn't be able to infer the same implementation from the simpler query so I have opened a github issue here.

like image 74
jjaderberg Avatar answered Sep 24 '22 01:09

jjaderberg