Extracting data from Neo4j with Cypher pattern matching
So far, we have put some data in Neo4j and explored it with Neo4j Browser. But unsurprisingly, Cypher also lets you select and return data programmatically. This is what is called pattern matching in the context of graphs.
Let’s analyze such a pattern:
MATCH (usr:User {birthPlace: "London"}) RETURN usr.name, usr.birthPlace
Here, we are selecting nodes with the User
label while filtering for nodes with birthPlace
equal to London
. The RETURN
statement asks Neo4j to only return the name and the birthPlace
property of the matched nodes. The result of the preceding query, based on the data created earlier, is as follows:
╒══════════╤════════════════╕ │"usr.name"│"usr.birthPlace"│ ╞══════════╪════════════════╡ │"Bob" │"London" │ ├──────────┼────────────────┤ │"Carol" │"London" │ ├──────────┼────────────────┤ │"Dave" │"London" │ └──────────┴────────────────┘
This is a simple MATCH
statement, but most of the time, you’ll need to traverse the graph somehow to explore relationships. This is where Cypher is very convenient. You can write queries with an easy-to-remember syntax, close to the one you would use when drafting your query on a piece of paper. As an example, let’s find the users known by Alice, and return their names:
MATCH (alice:User {name: "Alice"})-[:KNOWS]->(u:User) RETURN u.name
The highlighted part in the preceding query is a graph traversal. From the node(s) matching label, User
, and name, Alice
, we are traversing the graph toward another node through a relationship of the KNOWS
type. In our toy dataset, there is only one matching node, Bob
, since Alice
is connected to a single relationship of this type.
Note
In our example, we are using a single-node label and relationship type. You are encouraged to experiment by adding more data types. For instance, create some nodes with the Product
label and relationships of the SELLS
/BUYS
type between users and products to build more complex queries.