Some Basic and Useful Cypher Queries for Neo4J

Here are a few queries to help in getting started with Cypher and Neo4J.

When working with relational databases, you would look at the tables to understand the data and relationships. But since graph databases are 'schema-less' you must find other ways to learn about the data. Here are some Cypher queries to help you understand the information in a Neo4J database. Note that these queries are for Neo4J version 2.

 

Find the unique labels that appear in the database:

match n
return distinct labels(n)

 

 

Find the unique relationships that appear in the database:

match n-[r]-()
return distinct type(r)

 

 

Combine the previous two queries to return the unique combinations relationships and labels in the database:

match n-[r]-()
return distinct labels(n), type(r)

 

 

Find nodes that don't have any relationships:

start n=node(*)
match n-[r?]-()
where r is null
return n

 

 

Find all nodes that have a specific property:

start n=node(*)
match n
where has(n.someProperty)
return n

 

 

Find all nodes that have a specific relationship (regardless of the direction of the relationship):

start n=node(*)
match n-[:SOME_RELATIONSHIP]-()
return distinct n

 

 

Show the nodes and a count of the number of relationships that they have:

start n=node(*)
match n-[r]-()
return n, count(r) as rel_count
order by rel_count desc

 

 

Get a count of all nodes in your graph:

start n=node(*)
match n
return count(n)

 

To delete all nodes in a databse (first you have to delete all relationships)

start n=node(*)
match n-[r]-()
delete r

start n=node(*)
match n
delete n

 

A simple query to get nodes of a certain category that match a certain property

match (n:Person) where n.name="Tim" return n