neo4j Getting started with neo4j Cypher Query Language


This is the Cypher, Neo4j's query language. In many ways, Cypher is similar to SQL if you are familiar with it, except SQL refers to items stored in a table while Cypher refers to items stored in a graph.

First, we should start out by learning how to create a graph and add relationships, since that is essentially what Neo4j is all about.

CREATE (ab:Object { age: 30, destination: "England", weight: 99 })
  • You use CREATE to create data
  • To indicate a node, you use parenthesis: ()
  • The ab:Object part can be broken down as follows: a variable 'ab' and label 'Object' for the new node. Note that the variable can be anything, but you have to be consistent in a line of Cypher Query
  • To add properties to the node, use brackets: {} brackets

Next, we will learn about finding MATCHes

MATCH (abc:Object) WHERE abc.destination = "England" RETURN abc;

MATCH specifies that you want to search for a certain node/relationship pattern (abc:Object) refers to one node Pattern (with label Object) which store the matches in the variable abc. You can think of this entire line as the following

abc =  find the matches that is an Object WHERE the destination is England.

In this case, WHERE adds a constraint which is that the destination must be England. You must include a return at the end for all MATCH queries (neo4j will not accept just a Match...your query must always return some value [this also depends on what type of query you are writing...we will talk more about this later as we introduce the other types of queries you can make].

The next line will be explained in the future, after we go over some more elements of the Cypher Query Language. This is to give you a taste of what we can do with this language! Below, you will find an example which gets the cast of movies whose title starts with 'T'

MATCH (actor:Person)-[:ACTED_IN]->(movie:Movie)
WHERE movie.title STARTS WITH "T"
RETURN movie.title AS title, collect( AS cast

A complete list of commands and their syntax can be found at the official Neo4j Cypher Reference Card here.