What is Cypher? What is a Cypher

I’m not a cypher

Cypher is a graph query language that is used to query the Neo4j Database. Just like you use SQL to query a MySQL database, you would use Cypher to query the Neo4j Database.

Cypher is a graph query language used to query Neo4j databases. Just as you query a MySQL database with SQL, you can also query a Neo4j database with Cypher.

A simple example of a CYPher query:

Match (m:Movie) where m.released > 2000 RETURN m limit 5
Copy the code

Nodes and Relationships Nodes and Relationships

Nodes and relationships are the basic structure of a graph database.

Nodes Nodes

Nodes represent entities, and nodes in a graph database are similar to rows in a relational database. In the image below, we can see two types of nodes: Person and Movie. When writing cypher queries, the nodes are enclosed in parentheses – similar to (P :Person) p is a variable and Person is the type of node it represents.

Relationship between the Relationship

Two nodes can be connected by relationship. In the figure above, ACTED_IN, REVIEWED, PRODUCED, WROTE, DIRECTED are all the relationships that have been added to the corresponding type of nodes. When cypHER queries are written, relationships are enclosed in square brackets, such as [w:WORKS_FOR], where w is a variable and WORKS_FOR is the type of relationship to which W refers. Two nodes can have multiple relationships.

MATCH (p:Person)-[d:DIRECTED]-(m:Movie) where m.released > 2010 RETURN p,d,m

This query returns all Movie nodes with release dates after 2010 as well as the director Person node.

Labels tag

A label is the name or identifier of a node or relationship. In the figure below, Movie and Person are node tags, while ACTED_IN and VAT tags are relational tags.

When writing CYPher queries, tags are prefixed with colons, such as :Person or :ACTED_IN.

Node labels can be assigned to variables by prefixing the colon with the variable name.

For example, (p:Person) indicates that the p variable refers to the node of the Person tag. Similar to the relationship between variables and classes in object orientation.

MATCH (p:Person) RETURN p limit 20

Query only nodes of type Person (limiting to 20 items)

MATCH (n) RETURN n limit 20

Querying a Node of any type (Limiting to 20 items)

The Properties attribute

Properties are key-value pairs used to add properties to nodes and relationships. To query and return the specified attributes of a node, write:

MATCH (m:Movie) return m.title, m.released

Query the Movie node, but only return the title and released properties.

Create a Node Creates a Node

The Create statement can be used to Create new nodes or relationships.

Create (p:Person {name: 'John Doe'}) RETURN p

The above statement creates a new Person node with the name attribute ‘John Doe’.

throughMatchWhereStatement query node

The Match statement is used to find nodes that Match a particular pattern. This is the primary way to get data from the Neo4j database.

In most cases, Match is used to narrow the range of results for specific conditions.

Match (p:Person {name: 'Tom Hanks'}) RETURN p

Filtering based on basic string matches can only be done in this way (without using the WHERE statement).

For more complex filtering, including >, <, Starts With, Ends With, and so on, you can combine the WHERE statement.

MATCH (p:Person) where p.name = "Tom Hanks" RETURN p

Both statements return the same result.

For more information about where: neo4j.com/docs/cypher…

Merge Clause specifies the Merge Clause

The Merge is used to

  1. Matches existing nodes and binds them or
  2. Create new nodes and bind them

It is a combination of Match and Create, and allows you to specify additional actions if data is matched or created.

MERGE (p:Person {name: 'John Doe'}) ON MATCH SET p.lastLoggedInAt = timestamp() ON CREATE SET p.createdAt = timestamp() Return p

If the staff node does not exist, the above statement creates it. If the node already exists, it sets the attribute lastLoggedInAt = current timestamp. If the node does not exist and is newly created, it sets the property createdAt = current timestamp.

Create a Relationship

The relationship connects two nodes.

MATCH (p:Person), (m:Movie) WHERE p.name = "Tom Hanks" and m.title = "Cloud Atlas" CREATE (p)-[w:WATCHED]->(m) RETURN type(w)

The above statement creates a WATCHED relationship between the Peron and Movie nodes and returns the type of the relationship (WATCHED).

Relationship Types

In Neo4j, there are two kinds of relationships – incoming and outgoing

In the figure above, the Tom Hanks node is said to have an outgoing relationship, while the Cloud Atlas node is said to have an incoming relationship.

Relationships always have a direction. However, you just need to pay attention to where it’s useful.

To express efferent or afferent relationships in CYPher, we use → or ←.

Example –

MATCH (p:Person)-[r:ACTED_IN]->(m:Movie) RETURN p,r,m

In the above query, Person has an outgoing relationship and Movie has an incoming relationship.

Although in the case of the movie dataset, the direction of the relationship is not so important, it will return the same result even if no direction is indicated in the query.

MATCH (p:Person)-[r:ACTED_IN]-(m:Movie) RETURN p,r,m

So the query above that is not an arrow will return the same result.

The Clean up Clean up

After the experiment/test /demo is complete, you can delete the movie dataset.

Note:

  • If a relationship exists, the node cannot be deleted
  • Delete nodes and relationships together

Delete all Movie and Person nodes and their relationships

MATCH (n) DETACH DELETE n

Confirm the deletion result:

MATCH (n) RETURN n


Complex query example

Multi-hop query example:

Query nodes and relationships that have a 4-hop relationship with Person Kevin Bacon

MATCH (bacon:Person {name:"Kevin Bacon"})-[*0..4]-(hollywood) RETURN DISTINCT hollywood

Shortest path query example:

Query the shortest path between Kevin Bacon and Meg Ryan

MATCH p=shortestPath( (bacon:Person {name:"Kevin Bacon"})-[*]-(meg:Person {name:"Meg Ryan"}) ) RETURN p

Extend Tom Hanks co-actors, to find co-co-actors who haven’t worked with Tom Hanks…

Expand Tom Hanks costars to find costars who haven’t worked with Tom Hanks…

MATCH (tom:Person {name:"Tom Hanks"})-[:ACTED_IN]->(m)<-[:ACTED_IN]-(coActors), (coActors)-[:ACTED_IN]->(m2)<-[:ACTED_IN]-(cocoActors) WHERE NOT (tom)-[:ACTED_IN]->()<-[:ACTED_IN]-(cocoActors) AND tom  <> cocoActors RETURN cocoActors.name AS Recommended, count(*) AS Strength ORDER BY Strength DESCCopy the code

Find someone to introduce Tom Hanks to Tom Cruise

Get someone to introduce Tom Hanks to Tom Cruise

MATCH (tom:Person {name:"Tom Hanks"})-[:ACTED_IN]->(m)<-[:ACTED_IN]-(coActors),
  (coActors)-[:ACTED_IN]->(m2)<-[:ACTED_IN]-(cruise:Person {name:"Tom Cruise"})
RETURN tom, m, coActors, m2, cruise
Copy the code