Select Data with MATCH in Neo4j CQL
The MATCH clause in Neo4j CQL (Cypher Query Language) is used to find nodes and relationships in a graph database. In this tutorial, we will learn how to use the MATCH clause to select data from a Neo4j graph database.
Syntax
The general syntax for using the MATCH clause with Cypher in Neo4j is as follows:
MATCH pattern
WHERE condition
RETURN expression
pattern
: specifies the pattern of nodes and relationships to search for.condition
: used to filter the results based on certain criteria.expression
: what to return as the output.
Example
Consider the following graph database:
To select all the nodes in the database, we can use:
MATCH (n)
RETURN n
This will return all the nodes in the database:
╒═════════════════╕
│"n" │
╞═════════════════╡
│{"name":"Alice"} │
├─────────────────┤
│{"name":"Bob"} │
├─────────────────┤
│{"name":"Carol"} │
├─────────────────┤
│{"name":"Dave"} │
└─────────────────┘
Now, let's say we want to find all the FOLLOWS
relationships where the distance
attribute is greater than 2. We can use:
MATCH (a)-[r:FOLLOWS]->(b)
WHERE r.distance > 2
RETURN a.name, b.name, r.distance
This will return:
╒══════════╤══════════╤═══════════╕
│"a.name" │"b.name" │"r.distance"│
╞══════════╪══════════╪═══════════╡
│"Alice" │"Bob" │3 │
├──────────┼──────────┼───────────┤
│"Bob" │"Carol" │4 │
├──────────┼──────────┼───────────┤
│"Carol" │"Dave" │3 │
└──────────┴──────────┴───────────┘
Explanation
In the first example, MATCH (n)
matches all nodes in the database and RETURN n
returns all nodes that were matched.
In the second example, MATCH (a)-[r:FOLLOWS]->(b)
matches all the FOLLOWS
relationships in the database where node a
is the starting node, node b
is the ending node and r
is the relationship object. WHERE r.distance > 2
filters the results based on the condition that distance
is greater than 2 and RETURN a.name, b.name, r.distance
specifies what to return as the output.
Use
The MATCH clause is used in combination with the WHERE and RETURN clauses to select data from a Neo4j graph database. It allows for the retrieval of specific nodes and relationships based on specific criteria.
Important Points
- The MATCH clause is used to search for nodes and relationships in the graph database.
- The WHERE clause is used to filter the results based on a specific condition or criteria.
- The RETURN clause is used to specify what to return as the output of the query.
- The MATCH clause can be used in combination with other Cypher clauses like CREATE, SET, and DELETE to perform more complex operations.
Summary
In this tutorial, we learned how to use the MATCH clause in Neo4j CQL to select data from a graph database. We covered the syntax for using the MATCH clause with Cypher queries, examples of how to use the MATCH clause, and useful tips and important points to keep in mind when using the MATCH clause. Overall, the MATCH clause is an essential tool when working with Neo4j graph databases.