Our example graph consists of movies with title and year and actors with a name.
Actors have ACTS_IN
relationships to movies, which represents the role they played.
This relationship also has a role attribute.
We’ll go with three movies and three actors:
CREATE (matrix1:Movie { title : 'The Matrix', year : '1999-03-31' }) CREATE (matrix2:Movie { title : 'The Matrix Reloaded', year : '2003-05-07' }) CREATE (matrix3:Movie { title : 'The Matrix Revolutions', year : '2003-10-27' }) CREATE (keanu:Actor { name:'Keanu Reeves' }) CREATE (laurence:Actor { name:'Laurence Fishburne' }) CREATE (carrieanne:Actor { name:'Carrie-Anne Moss' }) CREATE (keanu)-[:ACTS_IN { role : 'Neo' }]->(matrix1) CREATE (keanu)-[:ACTS_IN { role : 'Neo' }]->(matrix2) CREATE (keanu)-[:ACTS_IN { role : 'Neo' }]->(matrix3) CREATE (laurence)-[:ACTS_IN { role : 'Morpheus' }]->(matrix1) CREATE (laurence)-[:ACTS_IN { role : 'Morpheus' }]->(matrix2) CREATE (laurence)-[:ACTS_IN { role : 'Morpheus' }]->(matrix3) CREATE (carrieanne)-[:ACTS_IN { role : 'Trinity' }]->(matrix1) CREATE (carrieanne)-[:ACTS_IN { role : 'Trinity' }]->(matrix2) CREATE (carrieanne)-[:ACTS_IN { role : 'Trinity' }]->(matrix3)
This gives us the following graph to play with:
Let’s check how many nodes we have now:
MATCH (n) RETURN "Hello Graph with " + count(*)+ " Nodes!" AS welcome;
Return a single node, by name:
MATCH (movie:Movie { title: 'The Matrix' }) RETURN movie;
Return the title and date of the matrix node:
MATCH (movie:Movie { title: 'The Matrix' }) RETURN movie.title, movie.year;
Which results in:
movie.title | movie.year |
---|---|
1 row | |
|
|
Show all actors:
MATCH (actor:Actor) RETURN actor;
Return just the name, and order them by name:
MATCH (actor:Actor) RETURN actor.name ORDER BY actor.name;
Count the actors:
MATCH (actor:Actor) RETURN count(*);
Get only the actors whose names end with “s”:
MATCH (actor:Actor) WHERE actor.name =~ ".*s$" RETURN actor.name;
Here’s some exploratory queries for unknown datasets. Don’t do this on live production databases!
Count nodes:
MATCH (n) RETURN count(*);
Count relationship types:
MATCH (n)-[r]->() RETURN type(r), count(*);
type(r) | count(*) |
---|---|
1 row | |
|
|
List all nodes and their relationships:
MATCH (n)-[r]->(m) RETURN n AS FROM , r AS `->`, m AS to;
from | -> | to |
---|---|---|
9 rows | ||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|