Inferensys

Glossary

Cypher

Cypher is a declarative graph query language, originally developed for Neo4j, that uses an ASCII-art syntax to express patterns for matching, creating, updating, and deleting nodes and relationships in a property graph.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
GRAPH QUERY LANGUAGE

What is Cypher?

Cypher is the declarative query language for property graph databases, most famously Neo4j, designed for intuitive pattern matching and data manipulation.

Cypher is a declarative graph query language that uses an intuitive, ASCII-art-inspired syntax to find patterns within a property graph. Its core syntax, (node)-[relationship]->(node), allows developers to express complex graph traversals and operations—such as MATCH, CREATE, SET, and DELETE—in a highly readable format. Unlike imperative languages, Cypher describes what data to find or modify, not how to retrieve it, enabling the database's query optimizer to determine the most efficient execution plan.

As a cornerstone of the property graph model, Cypher operates on nodes (entities) with labels and properties, connected by directed, typed relationships. It is integral to enterprise knowledge graphs for tasks like entity resolution, graph-based RAG, and complex graph analytics. While originally created for Neo4j, its influence led to the development of the open-source openCypher project and the international standard Graph Query Language (GQL), which aims to unify graph querying across vendors.

GRAPH QUERY LANGUAGE

Key Features of Cypher

Cypher is a declarative graph query language designed for the property graph model. Its intuitive, ASCII-art syntax allows developers to express complex graph patterns for matching, creating, updating, and deleting nodes and relationships.

01

ASCII-Art Pattern Matching

Cypher's core innovation is its visual, ASCII-art syntax for describing graph patterns. Nodes are represented by parentheses (), relationships by arrows --> or --, and properties by curly braces {}. This makes queries highly readable and intuitive, closely mirroring a whiteboard diagram.

Example: MATCH (p:Person)-[:LIVES_IN]->(c:City {name: 'Berlin'}) RETURN p.name

  • (p:Person) is a node with the label Person.
  • -[:LIVES_IN]-> is a directed relationship of type LIVES_IN.
  • (c:City {name: 'Berlin'}) is a target node with label City and a property filter.
02

Declarative Read & Write Clauses

Cypher uses a structured set of declarative clauses that describe what to find or do, not how to do it. The database's query optimizer determines the most efficient execution path.

Key Clauses:

  • MATCH: Describes patterns to find in the graph.
  • WHERE: Filters results with predicates.
  • RETURN: Defines the result set to output.
  • CREATE / MERGE: Creates new graph elements or ensures they exist.
  • SET / REMOVE: Updates or deletes properties and labels.
  • DELETE: Removes nodes and relationships.

Queries chain these clauses, e.g., MATCH a pattern, WHERE to filter, then RETURN results.

03

MERGE for Idempotent Operations

The MERGE clause ensures a pattern exists in the graph. It acts as a combination of MATCH and CREATE.

  • If the entire pattern already exists, MERGE simply matches it.
  • If any part is missing, it creates the missing elements.

This is critical for idempotent data loading and avoiding duplicates. It is often used with ON CREATE SET and ON MATCH SET to specify properties to set only on creation or update.

Example: MERGE (c:Company {taxId: '12345'}) ON CREATE SET c.founded = date() ON MATCH SET c.lastSeen = date() ensures a company node exists and updates timestamps appropriately.

04

Path Patterns & Variable-Length Relationships

Cypher excels at querying paths—sequences of connected nodes and relationships. It allows for expressive and efficient traversal queries.

  • Variable-length paths: Use * to match paths of unspecified depth.
    • (a)-[:KNOWS*1..3]->(b) finds paths where a KNOWS b via 1 to 3 hops.
    • (a)-[:KNOWS*]->(b) finds paths of any length.
  • Named paths: Assign an entire path to a variable for later use: path = (a)-[:KNOWS*2..4]->(b).
  • Shortest path functions: Built-in algorithms like shortestPath() find optimal routes.

This feature is fundamental for social network analysis, recommendation engines, and fraud detection.

05

Aggregation & List Comprehensions

Cypher provides powerful aggregation functions and list operations for transforming result sets, similar to SQL's GROUP BY but with graph-aware semantics.

Aggregation: Functions like collect(), count(), sum(), avg() group results by a key.

  • RETURN p.name, collect(c.name) AS cities returns a person's name and a list of their cities.

List & Map Projections: Create complex structures directly in the RETURN.

  • RETURN p {.name, .age, employer: [(p)-[:WORKS_FOR]->(c) | c.name]} projects a map with the person's properties and a derived list of employer names.

List Comprehensions: Process elements within a list: [x IN list WHERE x.prop > 10 | x.value].

06

ACID Transactions & Procedural Logic

Cypher queries execute within full ACID transactions, ensuring data integrity. Multiple statements in a single transaction are atomic.

For complex, multi-step operations, Cypher supports procedural logic through:

  • WITH Clause: Pipes results from one part of a query to the next, enabling step-wise transformations and conditional logic.
  • FOREACH Clause: Iterates over a list to perform updating operations.
  • CALL Subquery: Isolates sub-queries for modular logic.
  • User-Defined Procedures & Functions: Extend Cypher's capabilities with custom logic written in Java, Python, or other languages, callable via CALL my.procedure(input).

This combination allows Cypher to handle sophisticated data migration, graph algorithms, and ETL workflows.

GRAPH QUERY LANGUAGE

How Cypher Works: Syntax and Execution

Cypher is a declarative, ASCII-art-inspired query language for property graph databases, primarily associated with Neo4j. It allows users to express complex graph patterns for matching, creating, updating, and deleting nodes and relationships with a human-readable syntax.

Cypher's core syntax uses parentheses () to represent nodes, arrows --> or -- for relationships, and square brackets [] to specify relationship types and properties. The MATCH clause finds patterns, RETURN specifies what data to output, and WHERE adds filtering conditions. Its declarative nature means users describe what data they want, not how to traverse the graph, leaving optimization to the database engine. This leverages native graph storage features like index-free adjacency for fast traversals.

Execution begins with the query planner generating a logical plan, which is optimized into a physical execution plan that may use graph indexes and specific traversal algorithms. The engine processes patterns by anchoring on known starting points, then exploring connected paths. Cypher supports ACID transactions, allowing multiple operations to be grouped atomically. It is a precursor to the ISO-standard Graph Query Language (GQL), sharing many conceptual foundations for pattern matching and data manipulation.

GRAPH DATABASE SCHEMAS

Common Cypher Query Examples

Cypher's ASCII-art syntax makes graph patterns intuitive. These examples demonstrate core operations for matching, creating, updating, and deleting data in a property graph.

01

Basic Pattern Matching (MATCH)

The MATCH clause is used to find patterns in the graph. It describes the shape of the data using nodes in parentheses () and relationships in brackets [].

Example: Find a Person and their City

cypher
MATCH (p:Person)-[:LIVES_IN]->(c:City {name: 'London'})
RETURN p.name, p.age
  • (p:Person): A node with the label Person, assigned to variable p.
  • -[:LIVES_IN]->: A directed relationship of type LIVES_IN.
  • (c:City {name: 'London'}): A City node with a property name equal to 'London'.
  • The query returns the names and ages of all people who live in London.
02

Creating Nodes and Relationships (CREATE)

The CREATE clause is used to insert new graph elements. You can create nodes, relationships, and set their properties in a single statement.

Example: Create a New Person and Connect Them

cypher
CREATE (p:Person {
    name: 'Alice',
    employeeId: 123,
    joined: date()
})
WITH p
MATCH (c:City {name: 'Berlin'})
CREATE (p)-[:WORKS_IN {since: 2023}]->(c)
RETURN p, c
  • Creates a new Person node with three properties.
  • The WITH clause pipes the created node p to the next part of the query.
  • Matches an existing City node for Berlin.
  • Creates a new WORKS_IN relationship from Alice to Berlin, with a property since.
  • Note: CREATE will always create new data, even if it duplicates existing patterns.
03

Merging Data (MERGE)

The MERGE clause ensures a pattern exists in the graph. It will match an existing pattern or create it if it doesn't exist, preventing duplicates. It is often used with ON CREATE and ON MATCH.

Example: Get or Create a Unique Company

cypher
MERGE (c:Company {legalName: 'Inferensys Ltd'})
ON CREATE SET c.created = timestamp(), c.status = 'new'
ON MATCH SET c.lastAccessed = timestamp()
RETURN c
  • Attempts to find a Company node with legalName: 'Inferensys Ltd'.
  • ON CREATE: If the node is created, it sets the created and status properties.
  • ON MATCH: If the node already exists, it updates the lastAccessed property.
  • This is the Cypher equivalent of an "upsert" operation, critical for maintaining data integrity.
04

Updating Properties (SET, REMOVE)

The SET clause updates properties on nodes or relationships. REMOVE deletes properties or labels.

Example: Update a User's Profile

cypher
MATCH (u:User {userId: 'u456'})
SET u.department = 'Engineering',
    u.lastUpdated = datetime()
REMOVE u.temporaryFlag
RETURN u

Example: Add or Remove a Label

cypher
MATCH (p:Person {name: 'Bob'})
SET p:Archived  // Adds the 'Archived' label
// REMOVE p:Archived // Would remove the label
  • SET can add new properties or overwrite existing ones.
  • Labels are treated as a special type of property and can be added/removed with SET/REMOVE.
  • Combining MATCH with SET is the standard pattern for in-place updates.
05

Filtering and Aggregation (WHERE, WITH, ORDER BY)

Cypher uses WHERE for filtering patterns, WITH for piping and aggregating intermediate results, and ORDER BY for sorting.

Example: Complex Filtering and Counting

cypher
MATCH (p:Person)-[:WORKS_FOR]->(co:Company)
WHERE p.age > 25 AND co.industry = 'Technology'
WITH co, count(p) AS employeeCount
WHERE employeeCount > 50
RETURN co.name, employeeCount
ORDER BY employeeCount DESC
  • Finds people over 25 who work for tech companies.
  • WITH passes the company and a count of its matched employees to the next stage.
  • The second WHERE clause filters these aggregated results to only companies with more than 50 such employees.
  • Finally, results are returned sorted by the count in descending order. This demonstrates chaining query stages.
06

Path Finding and Variable-Length Relationships

Cypher excels at finding paths. Variable-length relationships use * to traverse an unspecified number of hops.

Example: Find Shortest Path

cypher
MATCH path = shortestPath(
  (a:Person {name: 'Alice'})-[*..6]-(b:Person {name: 'Bob'})
)
RETURN path, length(path)

Example: Find All Colleagues Up to 2 Hops Away

cypher
MATCH (p:Person {name: 'Charlie'})-[:WORKS_WITH*1..2]-(colleague:Person)
RETURN DISTINCT colleague.name
  • [*..6]: A path of any relationship type, up to 6 hops deep.
  • shortestPath(): A built-in function to find the shortest path matching the pattern.
  • [:WORKS_WITH*1..2]: Traverses WORKS_WITH relationships 1 or 2 hops out.
  • These patterns are fundamental for social network analysis, fraud detection (finding rings), and supply chain mapping.
FEATURE COMPARISON

Cypher vs. Other Graph Query Languages

A technical comparison of declarative query languages for property graphs and RDF triplestores, focusing on syntax, standardization, and core capabilities.

Feature / AspectCypherGQL (ISO Standard)SPARQLGremlin

Primary Data Model

Property Graph

Property Graph

RDF Triplestore

Property Graph

Query Paradigm

Declarative (Pattern Matching)

Declarative (Pattern Matching)

Declarative (Triple Pattern Matching)

Imperative (Traversal)

Standardization Body

OpenCypher (de facto), part of GQL

ISO (International Organization for Standardization)

W3C (World Wide Web Consortium)

Apache TinkerPop (de facto)

Core Syntax Style

ASCII-Art Pattern (e.g., (a)-[:KNOWS]->(b))

ASCII-Art Pattern (Cypher-influenced)

Triple Pattern (e.g., ?a :knows ?b)

Step-by-Step Traversal (e.g., g.V().out('knows'))

Schema Support

Schema-on-Write & Schema-on-Read

Schema-on-Write & Schema-on-Read

Schema-on-Read (RDFS/OWL ontologies)

Schema-on-Read

Path Query Support

Recursive Query Support

Built-in Graph Algorithms

ACID Transaction Support

Varies by triplestore

Varies by implementation

Primary Use Case

Business Intelligence & Pattern Discovery

Portable, Standardized Graph Queries

Semantic Web & Linked Data Integration

Graph Analytics & Complex Traversals

CYPHER QUERY LANGUAGE

Frequently Asked Questions

Cypher is the declarative query language for the Neo4j property graph database. Its intuitive, ASCII-art syntax allows developers to express complex graph patterns for matching, creating, updating, and deleting data. These FAQs address its core mechanics, use cases, and relationship to other standards.

Cypher is a declarative graph query language that uses an intuitive, ASCII-art-inspired syntax to find patterns within a property graph. Instead of specifying how to traverse the graph, you describe what the pattern looks like. The Cypher query processor then finds all subgraphs matching that pattern. A basic query like MATCH (p:Person)-[:LIVES_IN]->(c:City) RETURN p.name, c.name visually represents nodes in parentheses () and relationships in brackets -->, making graph exploration highly readable. It operates by pattern matching, filtering with a WHERE clause, and then returning or mutating the matched data.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.