Labels

In this lesson, you will learn how to add additional labels to existing nodes.

Add Labels to Existing Nodes

Adding labels to existing nodes can make your graph more useful and performant.

The Person nodes in the graph represent both actors and directors. To determine if a person is an actor or director, you need to query the ACTED_IN or DIRECTED relationships. Alternatively, you could add labels to the existing nodes to distinguish between actors and directors.

You can add labels to a node using SET, the syntax is:

cypher
MATCH (n)
SET n:Label

The following query would add the Actor label to all Person nodes that have acted in a movie:

cypher
MATCH (p:Person)-[:ACTED_IN]->()
SET p:Actor

The query:

  1. Finds all the Person nodes with an ACTED_IN relationship to a node

  2. Sets the Actor label to those nodes

As there are people in the database who have acted in more than one movie, you can use WITH DISTINCT to ensure that each person is only labeled once. Although not essential, this will improve the performance of the statement.

cypher
MATCH (p:Person)-[:ACTED_IN]->()
WITH DISTINCT p SET p:Actor

Add Actor label

Run the query to add the Actor label:

cypher
MATCH (p:Person)-[:ACTED_IN]->()
WITH DISTINCT p SET p:Actor

You can confirm it was successful by using the Actor label to find actors in the graph:

cypher
MATCH (a:Actor) RETURN a LIMIT 25

Filtering by labels is faster

By adding the Actor label to the graph, queries that use the label rather than the relationship will be quicker to return.

Check Your Understanding

Multiple labels?

True or False - A node can only have one label.

  • ❏ True

  • ✓ False

Hint

When setting a new label, the old label remains on the node.

Solution

The statement is False - Nodes can have multiple labels such as Person and Actor.

Summary

In this lesson, you learned how to add labels to existing nodes.

Next, you will create a Cypher statement to add a Director label to nodes with a DIRECTED relationship.

Chatbot

Hi, I am an Educational Learning Assistant for Intelligent Network Exploration. You can call me E.L.A.I.N.E.

How can I help you today?