By Nicole White, Data Scientist | February 3, 2016
Editor’s Note: Last October at GraphConnect San Francisco, Nicole White – Data Scientist at Neo Technology – delivered this presentation on how to write Cypher queries for your most common connected-data questions.
For more videos from GraphConnect SF and to register for GraphConnect Europe, check out graphconnect.com..
Cypher: Neo4j’s Graph Query Language
When you ask someone what they love about Neo4j, Cypher is always at the top. Cypher is essentially ASCII art; you draw out your desired graph pattern in your code.
A node is indicated with open and closed parentheses, a data relationship is indicated by open/close square brackets, and to specify a pattern you use hyphens in combination with the nodes and relationships.
If you want to find a “node-relationship-node” pattern, you include two parentheses, a hyphen, open/close square brackets, another hyphen followed by a node on the other side, indicated below:
With Cypher, you most commonly specify a relationship direction with the “greater than”
>or “less than”
<signs. The second row above shows that the node on the left has an outgoing relationship to the node on the right, while the third example shows the opposite.
An Example Dataset: StarCraft
Let’s examine an example dataset from the game StarCraft.
Below is a hierarchical tree of requirements that demonstrate the different types of buildings you can construct and their required components. For example, the below hierarchy indicates that to build a barracks, you first need to have a command center.
We imported this tech tree into Neo4j because it’s very good at storing, modeling and querying tree-like structures. Below is the resulting graph:
In this dataset, we only have two node labels —
Unit— while the relationship, which is the hierarchy of requirements, is labeled
Above, the blue
Factorynode in the center of the graph is a building that requires a
Barracks, which requires a
Supply Depot. There is an extensive hierarchy of building requirements that extends to the lowest node, which is typically the
The graph also indicates that
Unitshave requirements; for example, a
Starportwhich requires a
We also have
Buildsrelationships, which demonstrate what is built by the different
Buildings. For example, the
Additionally, resources — such as minerals and gas — are required in order to create
Buildings. The below example demonstrates the resource requirements for the
Query 1: What Units can be Built at the Barracks? The
The most important component when writing a query is the
MATCHclause, which is where you draw the graph pattern that will be retrieved by the query. In the below example, we indicate that we want to start with a node labeled
Building, which is included after a colon and surrounded by parentheses and is our entity type:
Here we’ve indicated that we want to find a
Buildingnode that has an outgoing
Buildrelationship to a
Unitnode. We chose to use the identifiers
uto precede the colons, which are now bound to the entities and can be used in the following clauses.
MATCHclause we have the
WHEREclause, which indicates that the type of building we want is
RETURNclause indicates the type of entities we want returned to us by our query.
Neo4j returns the following visual result of our data.
Query 2: Average Unit Cost
To find out the average cost of each unit, we use the same
MATCHclause but without the identifier on the
Buildsrelationship because we don’t want it in the
RETURN. However, we do include the
uidentifiers because we want those returned in the
The below table is the result of our query; it provides us with the name of the
Buildingand the average cost of each
Buildingin terms of minerals and gas.
In the above example, the
b.nameis unique, but this doesn’t need to be the case. You can have multiple buildings with the same name, and your query can return all of them unless you have a uniqueness constraint on that property, such as “buildings have to be unique by the name property.”
Query 3: What Buildings and Units are Unlocked by Construction of an Engineering Bay?
In StarCraft, once you’ve constructed a certain number of buildings and units, you can construct an Engineering Bay. This allows you to build even more components.
To find out what buildings and units can only be built once an Engineering Bay has been constructed, we need to traverse the
Requiresrelationship up one more level from the
In Query 2, we matched
Buildsrelationship. In this query, we are matching
Requiresrelationship, which is why we’ve applied the building label to the nodes on either side of the
Requiresrelationship. However, we’ve indicated a specific building type to the node on the far right,
Neo4j returns the following, with the
Engineering Bayin the middle and the immediate one-step-out buildings that are unlocked once the
Engineering Bayhas been constructed.
Query 4: Which Buildings Have No Dependencies?
Which buildings can we build right away without having any other
Unitson the map?
To answer this question, we include a pattern in the
WHEREclause. We aren’t inquiring about data relationships; our only requirement is the return of entities that don’t have any
As indicated below, there are three buildings that do not have any
Requiresrelationships attached to them: the
Supply Depot. In other words, these are the only buildings that you can construct from the very start of the game.
Query 5: Which Units Have Additional Requirements for Construction?
The prerequisite for constructing most units is simply related to a specific building. However, some have additional dependencies, which we indicate in the below
MATCHclause we’ve indicated that we want to find a
Unit, and the first additional requirement
Unit. In the first line of the
MATCHclause, we’ve bound the unit node to
u, which we also use in the second line of the
WHEREclause, we indicate with the less-than and greater-than signs that we don’t want entities returned that are the same (i.e., we don’t want units with a
Requiresrelationship that pointed back to the same
Below are the Neo4j results:
Query 6: What’s the Most Expensive Unit that Can Be Built at the Factory? Ordering and Limits
MATCHclause shows that a building builds a unit, and the
WHEREclause shows that the name of the building is
Factory. We want to return the name of the
Unit, as well as the amount of required mineral and gas it takes to build it.
You can use
LIMITright after the
RETURNclause, and request the results in descending order, i.e. from most expensive to least expensive.
LIMIT 1refers to the most expensive unit that can be built at this particular
Query 7: What Do the Barracks Unlock up to Two Levels Deep? Traversing Two-Level Relationships
Our prior queries have all included single-level relationships (i.e., the entities have been directly related). However, this is a “variable length” query. In this case, we want to
RETURNresults that are separated by both one and two degrees from the
Barracks. In the
MATCHclause, we indicate this by including an asterisk and the number 2 in our relationship:
Below are the results in Neo4j:
This map shows that the
Ghost Academy. Two steps away, the
Query 8: What Are All The Dependencies of the Starport Building? What Not To Do
To answer this query, we move from the
Starportnode all the way down the hierarchy, which you do by including an asterisk while omitting the “maximum” on the relationship:
This is not a good query, because it requires an exhaustive search of your entire database, and will only return the below:
It did the
Requiresrelationship all the way through the hierarchy until it didn’t have anywhere to go. This isn’t a great way to create a dependency, so let’s explore a better dependency with the
Battlecruiseras an example.
Query 9: What Are All The Buildings Required to Construct a Battlecruiser? Cypher’s Shortest Path Function
To address this query, we rely on Cypher’s
shortestPathfunction, which allows you to find the single shortest path between nodes. The syntax for this function is demonstrated below:
This query returns the following Neo4j graph:
Query 10: What Are All The Buildings Required to Construct a BattleCruiser and How Much Will It Cost? Cypher’s “Unwind” Function
To answer this query we rely on Cypher’s
UNWINDfunction, which allows you to expand a collection into a sequence of rows. In the below example, we grab the nodes out of a path, place those nodes into their own separate rows, and then
RETURNthe name and amount of resources required to build it:
The below table shows the amount of required resources to build each
Buildingin the Neo4j graph from Query 8:
Query 11: What Are All the Necessary Components to Build a Battlecruiser, and Where Does it Need to be Built? Multiple
To answer this question, we will need to write multiple
WHEREclauses. In the below example, our first two lines are identical to the previous “shortest path” example, and we’ve bound
Unitto the identifier
Neo4j then returns the following graph:
So that is how you can use multiple
MATCHclauses within a Cypher query.
Inspired by Nicole’s talk? Register for GraphConnect Europe on April 26, 2016 at for more industry-leading presentations and workshops on the evolving world of graph database technology.
About the Author
Nicole White, Data Scientist
Nicole White grew up in Kansas City, Missouri and then spent four years at LSU in Baton Rouge, Louisiana where she got a degree in economics with a minor in mathematics. She then went to the University of Texas at Austin where she got her masters degree in analytics, and it was during this time that she found Neo4j and began playing around with it. When she’s not graphing all the things, she spends her time playing card games and board games.
From the CEO
Have a Graph Question?
Reach out and connect with the Neo4j staff.Stackoverflow
Share your Graph Story?
Email us: email@example.com