Inferensys

Glossary

Cypher Query Language

Cypher is a declarative graph query language developed by Neo4j that uses an intuitive ASCII-art syntax to express patterns for retrieving and manipulating data stored in property graphs.
Data engineer managing feature store on laptop, feature definitions visible, casual data engineering session.
GRAPH QUERY LANGUAGE

What is Cypher Query Language?

Cypher is the declarative query language for the Neo4j graph database, designed specifically for retrieving and manipulating data stored as property graphs.

Cypher Query Language (CQL) is a declarative, ASCII-art syntax language for querying property graph databases, most notably Neo4j. It allows users to express complex graph patterns for data retrieval, updates, and administrative tasks by visually describing the desired connections between nodes and relationships using a concise, human-readable notation. Its core strength is in intuitive graph pattern matching, making it the industry standard for interacting with labeled property graphs.

Unlike SQL's tabular joins, Cypher's syntax mirrors the visual structure of a graph, using parentheses () for nodes and arrows --> for relationships. It supports CREATE, MATCH, MERGE, and DELETE clauses to manage graph data, and its WHERE clause filters results based on node/edge properties. For enterprise knowledge graphs, Cypher enables efficient traversal of deep relationship chains, which is fundamental for graph analytics, pathfinding, and powering graph-based RAG systems that require deterministic factual retrieval.

QUERY LANGUAGE

Key Features of Cypher

Cypher is a declarative graph query language developed by Neo4j that uses an intuitive ASCII-art syntax to express patterns for retrieving and manipulating data stored in property graphs.

01

ASCII-Art Pattern Matching

Cypher's most distinctive feature is its use of ASCII-art to visually represent graph patterns. Nodes are defined within parentheses (), and relationships are defined using arrows --> or --, with square brackets [] for details.

  • Example: (:Person)-[:WORKS_AT]->(:Company) intuitively reads as "a Person works at a Company."
  • This declarative syntax allows users to describe what they want from the graph, not how to traverse it procedurally, making queries more readable and writable than equivalent SQL joins or imperative code.
02

Property Graph Model Native

Cypher is natively designed for the property graph model, directly mapping its core constructs: nodes, relationships, properties, and labels.

  • Nodes ((n:Label {key: 'value'})) represent entities and can have multiple labels and key-value properties.
  • Relationships (-[r:TYPE {key: 'value'}]-) are directed, named connections that are first-class citizens with their own properties.
  • This native alignment eliminates the impedance mismatch common when using relational languages for graph data, enabling efficient storage and retrieval of connected data.
03

Declarative & Expressive Clauses

Cypher uses a structured set of declarative clauses that compose like sentences to build complex queries from simple parts.

Core clauses include:

  • MATCH: Describes the pattern to find in the graph.
  • WHERE: Filters patterns based on node/relationship properties or labels.
  • RETURN: Specifies what data to output.
  • CREATE/MERGE: Creates new graph elements or ensures they exist.
  • SET/REMOVE: Updates properties and labels.
  • DELETE: Removes elements.
  • WITH: Pipes query results between stages, enabling multi-pass queries for aggregation and post-processing.
04

Path Expressions & Variable-Length Relationships

Cypher excels at querying variable-depth connections, a complex task in relational systems. It uses a concise syntax to traverse paths of unknown or variable length.

  • Syntax: (:Person)-[:KNOWS*1..5]->(:Person) finds paths where one Person KNOWS another, from 1 to 5 hops away.
  • The asterisk * denotes the variable-length traversal, and the range 1..5 defines the minimum and maximum depth.
  • This enables powerful queries for finding shortest paths, discovering indirect connections, and analyzing network neighborhoods without recursive CTEs or multiple joins.
05

Graph-Specific Functions & Aggregations

The language includes built-in functions and aggregators specifically designed for graph analytics.

Key functions include:

  • Path functions: nodes(path), relationships(path), length(path).
  • Shortest path: shortestPath() and allShortestPaths() algorithms.
  • Aggregations on relationships: Collecting or counting across connections, e.g., COUNT(r) for incoming/outgoing edges.
  • List comprehensions & pattern comprehensions: Allow in-line filtering and projection of subgraph patterns directly within a RETURN clause, enabling complex result shaping.
06

Index-Free Adjacency & Query Optimization

Cypher queries are executed by a graph database engine (like Neo4j) that leverages index-free adjacency—a storage model where each node holds direct pointers to its connected relationships. This allows for constant-time traversals regardless of graph size.

  • The Cypher planner generates an execution plan that optimizes pattern matching order, index usage, and join strategies.
  • It supports parameterized queries ($param) for security and performance, preventing injection and enabling plan caching.
  • This combination allows Cypher to execute deep, multi-hop queries with millisecond latency on highly connected data, a performance profile central to its utility for real-time knowledge graph applications.
FEATURE COMPARISON

Cypher vs. Other Graph Query Languages

A technical comparison of declarative query languages for graph databases, focusing on syntax, expressiveness, and ecosystem integration.

Feature / MetricCypher (Neo4j)Gremlin (Apache TinkerPop)SPARQL (W3C RDF)

Primary Data Model

Property Graph

Property Graph

RDF Triplestore

Query Paradigm

Declarative (Pattern-Matching)

Imperative (Traversal)

Declarative (Triple Pattern)

Core Syntax Style

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

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

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

Schema Flexibility

Schema-Optional (Dynamic)

Schema-Optional (Dynamic)

Schema-First (via OWL/RDFS)

Built-in Path Finding

Built-in Graph Algorithms (Centrality, Community)

Standardization Body

openCypher / ISO-GQL (in progress)

Apache TinkerPop (De Facto)

World Wide Web Consortium (W3C)

Primary Use Case

Business Intelligence & Transactional OLTP

Flexible Graph Traversal & Analytics

Semantic Web & Linked Data Integration

CYPHER QUERY LANGUAGE

Common Cypher Query Examples

Cypher is a declarative graph query language for property graphs. Its ASCII-art syntax uses parentheses for nodes, arrows for relationships, and square brackets for details, making graph patterns intuitive to write and read.

01

Basic Node & Relationship Matching

The fundamental operation in Cypher is pattern matching. Use parentheses () to represent nodes and arrows --> or <-- to represent directed relationships.

  • Find all people: MATCH (p:Person) RETURN p
  • Find a person's friends: MATCH (p:Person)-[:FRIEND_OF]->(friend) WHERE p.name = 'Alice' RETURN friend
  • Find mutual connections: MATCH (a:Person)-[:FRIEND_OF]->(m)<-[:FRIEND_OF]-(b) WHERE a.name = 'Alice' AND b.name = 'Bob' RETURN m

The MATCH clause defines the pattern to find, WHERE filters results, and RETURN specifies what data to output.

02

Creating and Updating Data

Cypher uses CREATE, MERGE, SET, and DELETE to modify the graph.

  • Create a node with properties: CREATE (p:Person {name: 'Charlie', age: 30})
  • Merge a node (Create if not exists): MERGE (c:Company {name: 'Inferensys'}) ON CREATE SET c.founded = 2023
  • Create a relationship between existing nodes: MATCH (a:Person), (b:Person) WHERE a.name = 'Alice' AND b.name = 'Bob' CREATE (a)-[:WORKS_WITH]->(b)
  • Update a property: MATCH (p:Person {name: 'Charlie'}) SET p.age = 31
  • Delete a node and its relationships: MATCH (p:Person {name: 'Charlie'}) DETACH DELETE p

MERGE is crucial for ensuring data integrity and preventing duplicates.

03

Filtering and Aggregation

Use WHERE for conditional logic and aggregate functions like COUNT(), COLLECT(), and SUM() for data summarization.

  • Filter by property value: MATCH (p:Person) WHERE p.age > 25 RETURN p
  • Filter by string pattern: MATCH (p:Person) WHERE p.name STARTS WITH 'Al' RETURN p
  • Count nodes: MATCH (p:Person) RETURN COUNT(p) AS total_people
  • Group and aggregate: MATCH (p:Person)-[:WORKS_AT]->(c:Company) RETURN c.name, COLLECT(p.name) AS employees, COUNT(p) AS headcount
  • Order and limit results: MATCH (p:Person) RETURN p ORDER BY p.age DESC LIMIT 10

Aggregations implicitly group by non-aggregated columns in the RETURN clause.

04

Pathfinding and Variable-Length Relationships

Cypher excels at traversing paths of unknown depth using variable-length relationship patterns.

  • Find paths of any length: MATCH path = (a:Person)-[:FRIEND_OF*]->(b:Person) WHERE a.name = 'Alice' AND b.name = 'David' RETURN path
  • Find paths of length 1 to 3: MATCH (a)-[:CONNECTED_TO*1..3]->(b)
  • Find the shortest path: MATCH path = shortestPath((a:Person)-[:FRIEND_OF*]-(b:Person)) WHERE a.name = 'Alice' AND b.name = 'Zoe' RETURN path
  • Return path length and nodes: MATCH p = (a)-[*]->(b) RETURN length(p), nodes(p)

This is essential for recommendation systems, fraud detection (finding rings), and supply chain analysis.

05

Advanced Pattern: OPTIONAL MATCH & WITH

OPTIONAL MATCH and the WITH clause are powerful for constructing complex queries.

  • OPTIONAL MATCH returns null for missing parts of a pattern, acting like a LEFT OUTER JOIN: MATCH (p:Person) OPTIONAL MATCH (p)-[:HAS_DEGREE]->(d:Degree) RETURN p.name, d.type
  • The WITH clause pipes query results from one part to the next, enabling intermediate filtering and aggregation:
cypher
MATCH (p:Person)-[:PURCHASED]->(prod:Product)
WITH p, COUNT(prod) AS purchase_count
WHERE purchase_count > 5
RETURN p.name, purchase_count

WITH is key for breaking down complex queries into readable, logical stages.

06

List Comprehension and UNWIND

Cypher provides functional operations for processing collections.

  • List comprehension creates a list by filtering or transforming another list: RETURN [x IN range(1,10) WHERE x % 2 = 0 | x * 2] AS doubled_evens
  • UNWIND converts a list into individual rows, enabling batch operations:
cypher
WITH ['AI', 'Graphs', 'ML'] AS topics
UNWIND topics AS topic
MERGE (t:Topic {name: topic})
RETURN t
  • REDUCE aggregates elements in a list: MATCH p=(a)-[*]->(b) RETURN reduce(totalCost = 0, r IN relationships(p) | totalCost + r.cost) AS pathCost These constructs are vital for data transformation within a query.
CYPHER QUERY LANGUAGE

Frequently Asked Questions

Cypher is the declarative graph query language developed by Neo4j, designed specifically for the property graph model. Its intuitive, ASCII-art syntax allows developers and data scientists to express complex graph patterns for retrieving and manipulating connected data with remarkable clarity.

Cypher Query Language is a declarative, ASCII-art-inspired graph query language developed by Neo4j for querying and manipulating data stored in a property graph model. It allows users to express patterns of nodes and relationships using a visual, intuitive syntax, making it the standard language for interacting with Neo4j and other graph databases that support the openCypher project. Unlike imperative languages where you specify how to retrieve data, Cypher lets you declare what data pattern you want to find, and the query engine determines the most efficient execution path.

Its core components are:

  • Nodes: Represented by parentheses (), like (p:Person).
  • Relationships: Represented by arrows --> or --, like -[:KNOWS]->.
  • Properties: Key-value pairs stored within curly braces {}, like {name: 'Alice'}.
  • Labels and Relationship Types: Used for categorization and filtering, denoted by a colon :.

Cypher is designed for both online transaction processing (OLTP) for real-time queries and online analytical processing (OLAP) for complex graph analytics.

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.