77

I can't find how to return a node labels with Cypher.

Anybody knows the syntax for this operation?

Sovos
  • 3,330
  • 7
  • 25
  • 36

8 Answers8

103

To get all distinct node labels:

MATCH (n) RETURN distinct labels(n)

To get the node count for each label:

MATCH (n) RETURN distinct labels(n), count(*)
mkral
  • 4,065
  • 4
  • 28
  • 53
petra
  • 2,642
  • 2
  • 20
  • 12
  • 5
    `MATCH n RETURN DISTINCT LABELS(n)` is 8 characters less to type :) – F Lekschas Oct 14 '15 at 14:15
  • Agree with @FLekschas and moreover, Neo recommends that you use `MATCH` for newer Neo4j databases because `START` is for legacy indexes. – ADTC May 14 '16 at 08:10
  • `Neo.ClientError.Statement.SyntaxError Parentheses are required to identify nodes in patterns, i.e. (n) ...` (v. 3.1.1) – vladkras Mar 11 '17 at 06:09
  • 7
    This question also has `neo4j` tag in addition to `cypher`. The shortest to write (and fastest to execute!) query for getting all distinct node labels is `CALL db.labels` -- at least since `neo4j` 3.0, see also CALL page in `neo4j` [manual](https://neo4j.com/docs/developer-manual/3.0/cypher/clauses/call/) – unserializable May 28 '17 at 12:28
  • How can I return labels for a list of nodes? – user3701435 Aug 18 '18 at 14:13
63

There is a function labels(node) that can return all labels for a node.

Lisa Li
  • 2,562
  • 15
  • 11
41

Neo4j 3.0 has introduced the procedure db.labels() witch return all available labels in the database. Use:

call db.labels();
Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
25

If you want all the individual labels (not the combinations) you can always expand on the answers:

MATCH (n)
WITH DISTINCT labels(n) AS labels
UNWIND labels AS label
RETURN DISTINCT label
ORDER BY label
ErnestoE
  • 1,264
  • 13
  • 20
5
 START n=node(*) RETURN labels(n)
gaurav.singharoy
  • 3,751
  • 4
  • 22
  • 25
  • Results on this are currently a nightmare. Returns 1 row for every node. `START n=node(*) RETURN DISTINCT(labels(n))` returns the same as `MATCH (n) RETURN distinct labels(n)`, but takes ~10 times as long (on my db) – joshfindit Apr 30 '19 at 14:48
4

If you're using the Java API, you can quickly get an iterator of all the Labels in the database like so:

GraphDatabaseService db = (new GraphDatabaseFactory()).newEmbeddedDatabase(pathToDatabase);
ResourceIterable<Label> labs = GlobalGraphOperations.at(db).getAllLabels();
Ken Williams
  • 22,756
  • 10
  • 85
  • 147
4

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..

arganzheng
  • 1,294
  • 15
  • 20
0

match(n) where n.name="abc" return labels(n)

it returns all the labels of the node "abc"

Guest
  • 1