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:
MATCH (n)
SET n:LabelThe following query would add the Actor label to all Person nodes that have acted in a movie:
MATCH (p:Person)-[:ACTED_IN]->()
SET p:ActorThe query:
-
Finds all the
Personnodes with anACTED_INrelationship to a node -
Sets the
Actorlabel 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.
MATCH (p:Person)-[:ACTED_IN]->()
WITH DISTINCT p SET p:ActorAdd Actor label
Run the query to add the Actor label:
MATCH (p:Person)-[:ACTED_IN]->()
WITH DISTINCT p SET p:ActorYou can confirm it was successful by using the Actor label to find actors in the graph:
MATCH (a:Actor) RETURN a LIMIT 25Filtering by labels is faster
By adding theActor 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.