Appendix C: Cypher Quick Reference
Appendix C: Cypher Quick Reference
Section titled “Appendix C: Cypher Quick Reference”This appendix provides a quick reference for common Cypher patterns used with the Graph OLAP SDK. Cypher is the query language used to interact with graph instances.
Overview
Section titled “Overview”Cypher is a declarative graph query language that allows expressive and efficient pattern matching in property graphs. The SDK uses Cypher for all graph queries executed through the InstanceConnection.query() method.
Basic Query Structure
Section titled “Basic Query Structure”MATCH (pattern) // Find matching patternsWHERE condition // Filter resultsWITH variables // Chain query partsRETURN expression // Return resultsORDER BY field // Sort resultsLIMIT n // Limit result countNode Patterns
Section titled “Node Patterns”Match All Nodes
Section titled “Match All Nodes”// All nodesMATCH (n) RETURN n LIMIT 100
// Nodes with specific labelMATCH (c:Customer) RETURN c LIMIT 100
// Multiple labelsMATCH (n:Customer:Premium) RETURN n LIMIT 100Match by Property
Section titled “Match by Property”// Exact matchMATCH (c:Customer {name: 'Acme Corp'}) RETURN c
// With WHERE clauseMATCH (c:Customer)WHERE c.status = 'active'RETURN c
// Multiple conditionsMATCH (c:Customer)WHERE c.status = 'active' AND c.created_date > date('2024-01-01')RETURN cMatch by ID
Section titled “Match by ID”// Using internal node IDMATCH (n) WHERE id(n) = 123 RETURN n
// Using offset (for algorithm results)MATCH (n:Customer) WHERE offset(id(n)) = 42 RETURN nRelationship Patterns
Section titled “Relationship Patterns”Basic Relationships
Section titled “Basic Relationships”// Any directionMATCH (a:Customer)-[r]-(b:Customer) RETURN a, r, b
// Specific directionMATCH (a:Customer)-[r]->(b:Customer) RETURN a, r, b
// Specific relationship typeMATCH (a:Customer)-[r:KNOWS]->(b:Customer) RETURN a, r, b
// Multiple relationship typesMATCH (a)-[r:KNOWS|WORKS_WITH]->(b) RETURN a, r, bVariable-Length Paths
Section titled “Variable-Length Paths”// Path of length 1 to 3MATCH (a:Customer)-[*1..3]->(b:Customer) RETURN a, b
// Path of any lengthMATCH (a:Customer)-[*]->(b:Customer) RETURN a, b
// Shortest pathMATCH p = shortestPath((a:Customer)-[*]-(b:Customer))WHERE a.name = 'Acme' AND b.name = 'Beta'RETURN pPath Patterns
Section titled “Path Patterns”// Capture path as variableMATCH p = (a:Customer)-[:KNOWS*1..5]->(b:Customer)RETURN p, length(p) as path_length
// Extract nodes from pathMATCH p = (a)-[*1..3]->(b)RETURN nodes(p), relationships(p)Aggregation Functions
Section titled “Aggregation Functions”// Total countMATCH (n:Customer) RETURN count(n)
// Count distinctMATCH (c:Customer)-[:PURCHASED]->(p:Product)RETURN count(DISTINCT p)
// Count by groupMATCH (c:Customer)-[:PURCHASED]->(p:Product)RETURN p.category, count(*) as purchase_countORDER BY purchase_count DESCStatistical Aggregations
Section titled “Statistical Aggregations”// Sum, average, min, maxMATCH (c:Customer)RETURN sum(c.total_purchases) as total, avg(c.total_purchases) as average, min(c.total_purchases) as minimum, max(c.total_purchases) as maximum
// Standard deviationMATCH (c:Customer)RETURN stdev(c.total_purchases) as std_devCollect and Lists
Section titled “Collect and Lists”// Collect into listMATCH (c:Customer)-[:PURCHASED]->(p:Product)RETURN c.name, collect(p.name) as products
// Collect with limitMATCH (c:Customer)-[:PURCHASED]->(p:Product)RETURN c.name, collect(p.name)[0..5] as top_productsWorking with Properties
Section titled “Working with Properties”Accessing Properties
Section titled “Accessing Properties”// Single propertyMATCH (c:Customer) RETURN c.name
// Multiple propertiesMATCH (c:Customer) RETURN c.name, c.email, c.status
// All properties as mapMATCH (c:Customer) RETURN properties(c)Property Existence
Section titled “Property Existence”// Check property existsMATCH (c:Customer)WHERE c.email IS NOT NULLRETURN c
// Check property doesn't existMATCH (c:Customer)WHERE c.phone IS NULLRETURN cProperty Operations
Section titled “Property Operations”// String operationsMATCH (c:Customer)WHERE c.name STARTS WITH 'A'RETURN c
WHERE c.name ENDS WITH 'Corp'WHERE c.name CONTAINS 'Tech'WHERE c.name =~ '.*pattern.*' // Regex
// Numeric operationsMATCH (c:Customer)WHERE c.total_purchases > 1000 AND c.total_purchases <= 10000RETURN c
// List operationsMATCH (c:Customer)WHERE c.status IN ['active', 'pending']RETURN cWorking with Algorithm Results
Section titled “Working with Algorithm Results”After running algorithms, results are stored as node properties. Here’s how to query them:
Query Algorithm Results
Section titled “Query Algorithm Results”// PageRank scoresMATCH (c:Customer)WHERE c.pagerank_score IS NOT NULLRETURN c.name, c.pagerank_scoreORDER BY c.pagerank_score DESCLIMIT 10
// Community detection resultsMATCH (c:Customer)WHERE c.community_id IS NOT NULLRETURN c.community_id, count(*) as sizeORDER BY size DESC
// K-Core resultsMATCH (c:Customer)WHERE c.kcore_degree >= 5RETURN c.name, c.kcore_degreeCombine Algorithm Results
Section titled “Combine Algorithm Results”// High PageRank in large communitiesMATCH (c:Customer)WHERE c.pagerank_score > 0.01WITH c.community_id as community, count(*) as sizeWHERE size > 100MATCH (c2:Customer)WHERE c2.community_id = community AND c2.pagerank_score > 0.01RETURN c2.name, c2.pagerank_score, community, sizeORDER BY c2.pagerank_score DESCFind Central Nodes
Section titled “Find Central Nodes”// Top nodes by betweenness centralityMATCH (c:Customer)WHERE c.betweenness IS NOT NULLRETURN c.name, c.betweennessORDER BY c.betweenness DESCLIMIT 20
// Nodes connecting different communitiesMATCH (a:Customer)-[r]-(b:Customer)WHERE a.community_id <> b.community_idRETURN a.name, a.community_id, b.name, b.community_idLIMIT 50Path Analysis
Section titled “Path Analysis”Find Connections
Section titled “Find Connections”// Direct connectionsMATCH (a:Customer {name: 'Acme'})-[r]->(b)RETURN type(r), b.name
// Two-hop connectionsMATCH (a:Customer {name: 'Acme'})-[r1]->(intermediate)-[r2]->(b)RETURN intermediate.name, b.name
// All paths up to length 4MATCH p = (a:Customer {name: 'Acme'})-[*1..4]-(b:Customer {name: 'Beta'})RETURN p, length(p)ORDER BY length(p)Shortest Path Queries
Section titled “Shortest Path Queries”// Single shortest pathMATCH p = shortestPath( (a:Customer {name: 'Acme'})-[*]-(b:Customer {name: 'Beta'}))RETURN p, length(p)
// All shortest pathsMATCH p = allShortestPaths( (a:Customer {name: 'Acme'})-[*]-(b:Customer {name: 'Beta'}))RETURN p, length(p)Subgraph Queries
Section titled “Subgraph Queries”Extract Subgraph
Section titled “Extract Subgraph”// Ego network (1-hop neighborhood)MATCH (center:Customer {name: 'Acme'})-[r]-(neighbor)RETURN center, r, neighbor
// Extended ego network (2-hops)MATCH (center:Customer {name: 'Acme'})-[r1]-(n1)-[r2]-(n2)RETURN center, n1, n2, r1, r2Community Subgraph
Section titled “Community Subgraph”// All nodes and edges in a communityMATCH (a:Customer)-[r]-(b:Customer)WHERE a.community_id = 5 AND b.community_id = 5RETURN a, r, bResult Formatting
Section titled “Result Formatting”Return as Table
Section titled “Return as Table”// Named columnsMATCH (c:Customer)RETURN c.name AS customer_name, c.status AS status, c.total_purchases AS purchasesORDER BY purchases DESCLIMIT 10Return as Maps
Section titled “Return as Maps”// Return as mapMATCH (c:Customer)RETURN { name: c.name, status: c.status, purchases: c.total_purchases} AS customer_dataDistinct Results
Section titled “Distinct Results”// Remove duplicatesMATCH (c:Customer)-[:PURCHASED]->(p:Product)RETURN DISTINCT p.category
// Distinct with orderingMATCH (c:Customer)-[:PURCHASED]->(p:Product)RETURN DISTINCT p.categoryORDER BY p.categorySDK Query Examples
Section titled “SDK Query Examples”Basic Query
Section titled “Basic Query”# Execute Cypher queryresult = conn.query("MATCH (n:Customer) RETURN count(n) as total")print(result.rows) # [[1000]]
# With parametersresult = conn.query( "MATCH (c:Customer) WHERE c.status = $status RETURN c.name", {"status": "active"})Convert to DataFrame
Section titled “Convert to DataFrame”# Query with column namesresult = conn.query(""" MATCH (c:Customer) RETURN c.name AS name, c.status AS status, c.total_purchases AS purchases ORDER BY purchases DESC LIMIT 100""")
# Convert to Polars DataFramedf = result.to_polars()print(df.head())
# Convert to Pandas DataFramedf_pandas = result.to_pandas()Handle Large Results
Section titled “Handle Large Results”# Use LIMIT for large datasetsresult = conn.query(""" MATCH (c:Customer) RETURN c.name, c.pagerank_score ORDER BY c.pagerank_score DESC LIMIT 1000""")
# Paginated queriesdef fetch_paginated(conn, page_size=1000): offset = 0 while True: result = conn.query(f""" MATCH (c:Customer) RETURN c.name ORDER BY c.name SKIP {offset} LIMIT {page_size} """) if not result.rows: break yield result.rows offset += page_sizePerformance Tips
Section titled “Performance Tips”Use Indexes
Section titled “Use Indexes”For large graphs, ensure properties used in WHERE clauses are indexed:
-- Indexed lookups are fasterMATCH (c:Customer)WHERE c.customer_id = '12345' -- If customer_id is indexedRETURN cLimit Early
Section titled “Limit Early”Apply LIMIT as early as possible:
-- Better: limit earlyMATCH (c:Customer)WHERE c.status = 'active'WITH c LIMIT 100MATCH (c)-[:PURCHASED]->(p:Product)RETURN c.name, collect(p.name)
-- Worse: limit lateMATCH (c:Customer)-[:PURCHASED]->(p:Product)WHERE c.status = 'active'RETURN c.name, collect(p.name)LIMIT 100Avoid Cartesian Products
Section titled “Avoid Cartesian Products”Be explicit about relationships:
-- Bad: creates cartesian productMATCH (a:Customer), (b:Product)RETURN a, b
-- Good: explicit relationshipMATCH (a:Customer)-[:PURCHASED]->(b:Product)RETURN a, bUse WITH for Chaining
Section titled “Use WITH for Chaining”Break complex queries into stages:
-- Chain with WITHMATCH (c:Customer)WHERE c.status = 'active'WITH c, c.total_purchases as purchasesWHERE purchases > 1000MATCH (c)-[:PURCHASED]->(p:Product)WITH c, collect(DISTINCT p.category) as categoriesWHERE size(categories) >= 3RETURN c.name, categoriesSee Also
Section titled “See Also”- Algorithm Reference - Available algorithms
- Error Codes - Error handling
- SDK Quick Start - Getting started