Graph database query

An Introduction to Cypher
April 9, 2017 – 02:42 pm
RDBMS & Graphs: SQL vs. Cypher Query Languages

It allows us to state what we want to select, insert, update or delete from our graph data without requiring us to describe exactly how to do it.

Nodes

Cypher uses ASCII-Art to represent patterns. We surround nodes with parentheses which look like circles, e.g. (node). If we later want to refer to the node, we’ll give it an variable like (p) for person or (t) for thing. In real-world queries, we’ll probably use longer, more expressive variable names like (person) or (thing). If the node is not relevant to your question, you can also use empty parentheses.

Usually, the relevant labels of the node are provided to distinguish between entities and optimize execution, like (p:Person).

We might use a pattern like (person:Person)->(thing:Thing) so we can refer to them later, for example, to access properties like person.name and thing.quality.

The more general structure is:

MATCH (node:Label) RETURN node.property MATCH (node1:Label1)->(node2:Label2) WHERE node1.propertyA = {value} RETURN node2.propertyA, node2.propertyB

Please note that node-labels, relationship-types and property-names are case-sensitive in Cypher. All the other clauses, keywords and functions are not, but should be cased consistently according to the style used here.

Relationships

To fully utilize the power of our graph database we want to express more complex patterns between our nodes. Relationships are basically an arrow -> between two nodes. Additional information can be placed in square brackets inside of the arrow.

  • relationship-types like -[:KNOWS|:LIKE]->
  • a variable name -[rel:KNOWS]-> before the colon
  • additional properties -[{since:2010}]->
  • structural information for paths of variable length -[:KNOWS*..4]->

To access information about a relationship, we can assign it a variable, for later reference. It is placed in front of the colon -[rel:KNOWS]-> or stands alone -[rel]->.

If you forget the colon in front of a relationship-type, like this -[KNOWS]-> it does represent a variable and the relationship has no relationship-type declared.

MATCH (n1:Label1)-[rel:TYPE]->(n2:Label2) WHERE rel.property > {value} RETURN rel.property, type(rel)

Patterns

Nodes and relationship expressions are the building blocks for more complex patterns. Patterns can be written continuously or separated with commas. You can refer to variables declared earlier or introduce new ones.

  • friend-of-a-friend (user)-[:KNOWS]-(friend)-[:KNOWS]-(foaf)
  • shortest path: path = shortestPath( (user)-[:KNOWS*..5]-(other) )
  • collaborative filtering (user)-[:PURCHASED]->(product)(otherProduct)
  • tree navigation (root)(data:Product)

Patterns can be used to MATCH and CREATE data, but also (evaluating to a list of paths) in expressions, predicates and results.

Source: neo4j.com
Related Posts