Inferensys

Glossary

Cypher Query Language

Cypher is a declarative graph query language, developed for Neo4j, that uses an ASCII-art syntax to specify 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 OPTIMIZATION

What is Cypher Query Language?

Cypher is a declarative graph query language developed for the Neo4j graph database, designed to intuitively express complex graph patterns for data retrieval and manipulation.

Cypher Query Language (CQL) is a declarative, ASCII-art-inspired language for querying and updating property graphs. Its core syntax uses parentheses () for nodes, arrows --> for relationships, and square brackets [] for relationship details, allowing users to visually describe the graph patterns they wish to find, create, or modify. As a declarative language, users specify what data they want, not how to retrieve it, leaving the query optimization and execution to the underlying graph database engine.

Cypher supports standard CRUD operations (CREATE, READ, UPDATE, DELETE), complex filtering, aggregation, and pathfinding. It is integral to enterprise knowledge graphs for its ability to intuitively traverse connected data. While initially created for Neo4j, its openCypher variant has influenced the GQL international standard initiative. For optimization, Cypher compiles queries into execution plans that leverage techniques like index-free adjacency, predicate pushdown, and cost-based optimization to ensure efficient traversal of large-scale graphs.

GRAPH QUERY LANGUAGE

Key Features of Cypher

Cypher is a declarative graph query language, developed for Neo4j, that uses an ASCII-art syntax to specify patterns for matching, creating, updating, and deleting nodes and relationships in a property graph.

01

ASCII-Art Pattern Matching

Cypher's most distinctive feature is its use of ASCII-art to visually represent graph patterns. Nodes are depicted with parentheses (), relationships with arrows --> or <--, and properties with curly braces {}. This syntax makes complex graph traversals intuitive to read and write.

  • Example: MATCH (p:Person)-[:LIVES_IN]->(c:City {name:'London'}) RETURN p.name
  • The pattern (p:Person)-[:LIVES_IN]->(c:City) directly mirrors the visual structure of the graph, connecting a Person node to a City node via a LIVES_IN relationship.
02

Declarative Syntax

Cypher is a declarative language, meaning you specify what data you want, not how to retrieve it. The query optimizer determines the most efficient execution plan (scan, index, join order). This separates query logic from execution mechanics, improving developer productivity and allowing the database engine to apply advanced optimizations like predicate pushdown and cost-based optimization.

  • You declare patterns (MATCH), filters (WHERE), and results (RETURN).
  • The engine handles traversal algorithms, index selection, and join ordering.
03

Clause-Based Structure

Cypher queries are composed of distinct, chainable clauses, each serving a specific purpose in the query pipeline. This modular structure promotes readability and logical flow.

Core clauses include:

  • MATCH: Describes the graph pattern to find.
  • WHERE: Adds constraints to filter patterns.
  • 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 results between query parts, enabling complex multi-step operations.
04

Property Graph Model Native

Cypher is natively designed for the labeled property graph (LPG) model. This model's core components—nodes, relationships, labels, and properties—are first-class citizens in the language.

  • Nodes: (:Person {name: 'Alice', age: 30})
  • Relationships: Have direction, a type (e.g., :KNOWS), and can also hold properties [:KNOWS {since: 2019}].
  • Labels (e.g., Person, Movie) group nodes and enable schema-like constraints and indexing.
  • This native alignment allows Cypher to leverage storage optimizations like index-free adjacency for ultra-fast traversals.
05

Expressiveness for Complex Patterns

Cypher excels at expressing complex, multi-hop graph patterns and path queries concisely. It provides powerful operators for variable-length paths, optional patterns, and path filtering.

Key pattern features:

  • Variable-length Paths: (a)-[:FRIEND_OF*1..5]->(b) finds paths of 1 to 5 FRIEND_OF hops.
  • Shortest Path: Built-in shortestPath() function for finding optimal routes.
  • Optional Matching: OPTIONAL MATCH returns null for missing parts, acting like an outer join.
  • Path Variables: Assign a path to a variable for later use: p = (a)-[*]->(b).
06

Integration with Graph Algorithms

Cypher seamlessly integrates with graph analytics, allowing queries to invoke built-in graph algorithms and use their results for further filtering or aggregation. This blurs the line between transactional querying and analytical processing.

  • Examples: MATCH (p:Person) RETURN p.name, centrality.pageRank(p)
  • Algorithms like PageRank, community detection (Louvain), and shortest path (Dijkstra) can be called directly within a RETURN or WHERE clause.
  • This enables powerful insights, such as finding influential entities or clustered communities, within a single query.
FEATURE COMPARISON

Cypher vs. Other Graph Query Languages

A technical comparison of declarative graph query languages, focusing on syntax, model support, and optimization paradigms.

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

Primary Data Model

Labeled Property Graph (LPG)

Property Graph (via TinkerPop)

RDF Triplestore

Query Paradigm

Declarative (ASCII-art patterns)

Imperative / Functional traversal

Declarative (triple patterns)

Core Optimization Strategy

Cost-Based Optimization (CBO) with heuristic rules

Traversal strategy optimization

Heuristic Optimization with some CBO extensions

Native Storage Principle

Index-Free Adjacency

Varies by implementation (e.g., JanusGraph)

Triple/Quad indexing (PSO, POS, etc.)

Join Ordering Optimization

Predicate Pushdown Support

Approximate Query Processing (AQP) Integration

Via plugins and sampling functions

Limited; depends on underlying engine

Via SPARQL 1.1 subqueries and SAMPLE

Adaptive Query Processing (AQP) Support

In development / experimental

Vectorized Execution

Just-In-Time (JIT) Compilation

For certain operators in Neo4j 5+

Standardized Cardinality Estimation

Primary Use Case

Business analytics, pattern matching on LPGs

Graph algorithm exploration, complex pathfinding

Semantic web integration, ontology querying

Typical Latency for 3-hop Traversal

< 10 ms

10-100 ms (highly implementation-dependent)

50-500 ms (depends on triple index complexity)

GRAPH QUERY LANGUAGE

Common Cypher Query Examples

Cypher is a declarative graph query language for Neo4j that uses an intuitive ASCII-art syntax to find patterns. These examples demonstrate its core operations for matching, creating, updating, and analyzing property graphs.

01

Basic Pattern Matching (MATCH)

The MATCH clause is used to find patterns in the graph. It is the primary mechanism for reading data.

  • Find a person named 'Alice': MATCH (p:Person {name: 'Alice'}) RETURN p
  • Find Alice's friends: MATCH (p:Person {name: 'Alice'})-[:FRIEND_OF]->(friend) RETURN friend.name
  • Find patterns of variable length: Use * for variable-length traversals. MATCH (p:Person)-[:FRIEND_OF*1..3]->(fof) RETURN DISTINCT fof.name finds friends up to 3 hops away.
02

Creating Nodes and Relationships (CREATE)

The CREATE clause is used to insert new nodes and relationships into the graph.

  • Create a node with a label and properties: CREATE (p:Person {name: 'Bob', age: 30})
  • Create a relationship between existing nodes: First find the nodes, then create the link.
code
MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
CREATE (a)-[:WORKS_WITH {since: 2020}]->(b)
  • Create a full pattern in one statement: CREATE (c:Company {name: 'Acme'})<-[:WORKS_AT]-(p:Person {name: 'Charlie'})
03

Updating Properties (SET) and Merging (MERGE)

SET updates properties on nodes or relationships. MERGE ensures a pattern exists, creating it if it doesn't (a 'get or create' operation).

  • Update a property: MATCH (p:Person {name: 'Alice'}) SET p.age = 31
  • Merge a node (create if not exists): MERGE (p:Person {name: 'David'}) ON CREATE SET p.created = timestamp()
  • Merge a relationship: This ensures the connection exists without creating duplicate nodes.
code
MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MERGE (a)-[:FRIEND_OF]->(b)
04

Filtering and Aggregation (WHERE, WITH, RETURN)

Combine WHERE for filtering, WITH for piping intermediate results, and RETURN for final projection and aggregation.

  • Filter with WHERE: MATCH (p:Person) WHERE p.age > 25 RETURN p.name
  • Aggregate results: MATCH (p:Person)-[:WORKS_AT]->(c:Company) RETURN c.name, count(p) AS employeeCount
  • Chain operations with WITH: WITH is like a pipeline. This finds people, filters, then counts:
code
MATCH (p:Person)
WITH p WHERE p.age >= 18
RETURN count(p) AS adults
05

Path Finding and Shortest Path

Cypher has built-in functions for finding paths between nodes, which is a core strength of graph databases.

  • Find any path: MATCH path = (a:Person {name: 'Alice'})-[:FRIEND_OF|WORKS_WITH*..5]-(b:Person {name: 'Zoe'}) RETURN path
  • Find the shortest path: Use the shortestPath() function. This finds the fewest relationships connecting two nodes.
code
MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Zoe'})
MATCH p = shortestPath((a)-[*..15]-(b))
RETURN p
  • Find all shortest paths: Use allShortestPaths() to find all paths tied for the shortest length.
06

Deleting Elements (DELETE, DETACH DELETE)

DELETE removes nodes or relationships. DETACH DELETE removes a node and all its connected relationships.

  • Delete a relationship: MATCH (a:Person {name: 'Alice'})-[r:FRIEND_OF]->(b:Person {name: 'Bob'}) DELETE r
  • Delete a node (must have no relationships): MATCH (p:Person {name: 'Charlie'}) DELETE p
  • Force delete a node and its relationships: MATCH (p:Person {name: 'David'}) DETACH DELETE p
  • Delete all data: MATCH (n) DETACH DELETE n - Use with extreme caution.
CYPHER QUERY LANGUAGE

Frequently Asked Questions

Cypher is the declarative graph query language for Neo4j, designed for intuitive pattern matching and manipulation of property graphs. These FAQs address its core mechanics, optimization, and role in enterprise systems.

Cypher is a declarative graph query language, originally developed for the Neo4j graph database, that uses an intuitive ASCII-art syntax to specify patterns for matching, creating, updating, and deleting nodes and relationships in a property graph. Unlike imperative languages, you describe what data you want, not how to retrieve it, leaving the optimization and execution to the database engine. Its core abstraction is the Labeled Property Graph (LPG), where nodes (circles) and relationships (arrows) can have labels and properties. A basic pattern like (p:Person)-[:LIVES_IN]->(c:City) reads naturally as "a Person node, labeled Person, with a LIVES_IN relationship to a City node." Cypher is central to enterprise knowledge graphs for its ability to express complex, connected queries concisely.

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.