neo4j-cypher-guide
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNeo4j Modern Cypher Query Guide
Neo4j 现代Cypher查询指南
This skill helps generate Neo4j Cypher read queries using modern syntax patterns and avoiding deprecated features. It focuses on efficient query patterns for graph traversal and data retrieval.
本技能可帮助你使用现代语法模式生成Neo4j Cypher读取查询,同时避免使用废弃特性。它专注于用于图遍历和数据检索的高效查询模式。
Quick Compatibility Check
快速兼容性检查
When generating Cypher queries, immediately avoid these REMOVED features:
- ❌ function → Use
id()elementId() - ❌ Implicit grouping keys → Use explicit WITH clauses
- ❌ Pattern expressions for lists → Use pattern comprehension or COLLECT subqueries
- ❌ Repeated relationship variables → Use unique variable names
- ❌ Automatic list to boolean coercion → Use explicit checks
生成Cypher查询时,请立即避免以下已移除的特性:
- ❌ 函数 → 改用
id()elementId() - ❌ 隐式分组键 → 改用显式WITH子句
- ❌ 用于列表的模式表达式 → 改用模式推导或COLLECT子查询
- ❌ 重复的关系变量 → 使用唯一变量名
- ❌ 列表自动转换为布尔值 → 改用显式检查
Core Principles for Query Generation
查询生成核心原则
- Use modern syntax patterns - QPP for complex traversals, CALL subqueries for complex reads
- Optimize during traversal - Filter early within patterns, not after expansion
- Always filter nulls when sorting - Add IS NOT NULL checks for sorted properties
- Explicit is better than implicit - Always use explicit grouping and type checking
- 使用现代语法模式 - 复杂遍历使用QPP,复杂读取使用CALL子查询
- 遍历过程中优化 - 在模式内尽早过滤,而非扩展后过滤
- 排序时始终过滤空值 - 为排序属性添加IS NOT NULL检查
- 显式优于隐式 - 始终使用显式分组和类型检查
Critical Sorting Rule
关键排序规则
ALWAYS filter NULL values when sorting:
cypher
// WRONG - May include null values
MATCH (n:Node)
RETURN n.name, n.value
ORDER BY n.value
// CORRECT - Filter nulls before sorting
MATCH (n:Node)
WHERE n.value IS NOT NULL
RETURN n.name, n.value
ORDER BY n.value排序时务必过滤NULL值:
cypher
// WRONG - May include null values
MATCH (n:Node)
RETURN n.name, n.value
ORDER BY n.value
// CORRECT - Filter nulls before sorting
MATCH (n:Node)
WHERE n.value IS NOT NULL
RETURN n.name, n.value
ORDER BY n.valueQuery Pattern Selection Guide
查询模式选择指南
For Simple Queries
简单查询
Use standard Cypher patterns with modern syntax:
cypher
MATCH (n:Label {property: value})
WHERE n.otherProperty IS :: STRING
RETURN n使用带有现代语法的标准Cypher模式:
cypher
MATCH (n:Label {property: value})
WHERE n.otherProperty IS :: STRING
RETURN nFor Variable-Length Paths
可变长度路径
Consider Quantified Path Patterns (QPP) for better performance:
cypher
// Instead of: MATCH (a)-[*1..5]->(b)
// Use: MATCH (a)-[]-{1,5}(b)
// With filtering:
MATCH (a)((n WHERE n.active)-[]->(m)){1,5}(b)考虑使用量化路径模式(QPP)以获得更好的性能:
cypher
// Instead of: MATCH (a)-[*1..5]->(b)
// Use: MATCH (a)-[]-{1,5}(b)
// With filtering:
MATCH (a)((n WHERE n.active)-[]->(m)){1,5}(b)For Aggregations
聚合操作
Use COUNT{}, EXISTS{}, and COLLECT{} subqueries:
cypher
MATCH (p:Person)
WHERE count{(p)-[:KNOWS]->()} > 5
RETURN p.name,
exists{(p)-[:MANAGES]->()} AS isManager使用COUNT{}、EXISTS{}和COLLECT{}子查询:
cypher
MATCH (p:Person)
WHERE count{(p)-[:KNOWS]->()} > 5
RETURN p.name,
exists{(p)-[:MANAGES]->()} AS isManagerFor Complex Read Operations
复杂读取操作
Use CALL subqueries for sophisticated data retrieval:
cypher
MATCH (d:Department)
CALL (d) {
MATCH (d)<-[:WORKS_IN]-(p:Person)
WHERE p.salary IS NOT NULL // Filter nulls
WITH p ORDER BY p.salary DESC
LIMIT 3
RETURN collect(p.name) AS topEarners
}
RETURN d.name, topEarners使用CALL子查询进行复杂数据检索:
cypher
MATCH (d:Department)
CALL (d) {
MATCH (d)<-[:WORKS_IN]-(p:Person)
WHERE p.salary IS NOT NULL // Filter nulls
WITH p ORDER BY p.salary DESC
LIMIT 3
RETURN collect(p.name) AS topEarners
}
RETURN d.name, topEarnersCommon Query Transformations
常见查询转换
Counting Patterns
计数模式
cypher
// Old: RETURN size((n)-[]->())
// Modern: RETURN count{(n)-[]->()}cypher
// Old: RETURN size((n)-[]->())
// Modern: RETURN count{(n)-[]->()}Checking Existence
存在性检查
cypher
// Old: WHERE exists((n)-[:REL]->())
// Modern: WHERE EXISTS {MATCH (n)-[:REL]->()}
// Also valid: WHERE exists{(n)-[:REL]->()}cypher
// Old: WHERE exists((n)-[:REL]->())
// Modern: WHERE EXISTS {MATCH (n)-[:REL]->()}
// Also valid: WHERE exists{(n)-[:REL]->()}Element IDs
元素ID
cypher
// Old: WHERE id(n) = 123
// Modern: WHERE elementId(n) = "4:abc123:456"
// Note: elementId returns a string, not integercypher
// Old: WHERE id(n) = 123
// Modern: WHERE elementId(n) = "4:abc123:456"
// Note: elementId returns a string, not integerSorting with Null Handling
含空值处理的排序
cypher
// Always add null check
MATCH (n:Node)
WHERE n.sortProperty IS NOT NULL
RETURN n
ORDER BY n.sortProperty
// Or use NULLS LAST
MATCH (n:Node)
RETURN n
ORDER BY n.sortProperty NULLS LASTcypher
// Always add null check
MATCH (n:Node)
WHERE n.sortProperty IS NOT NULL
RETURN n
ORDER BY n.sortProperty
// Or use NULLS LAST
MATCH (n:Node)
RETURN n
ORDER BY n.sortProperty NULLS LASTWhen to Load Reference Documentation
何时加载参考文档
Load the appropriate reference file when:
在以下场景加载对应的参考文件:
references/deprecated-syntax.md
references/deprecated-syntax.md
- Migrating queries from older Neo4j versions
- Encountering syntax errors with legacy queries
- Need complete list of removed/deprecated features
- 从旧版Neo4j迁移查询
- 遇到遗留查询的语法错误
- 需要完整的已移除/废弃特性列表
references/subqueries.md
references/subqueries.md
- Working with CALL subqueries for reads
- Using COLLECT or COUNT subqueries
- Handling complex aggregations
- Implementing sorting with null filtering
- 使用CALL子查询进行读取操作
- 使用COLLECT或COUNT子查询
- 处理复杂聚合
- 实现含空值过滤的排序
references/qpp.md
references/qpp.md
- Optimizing variable-length path queries
- Need early filtering during traversal
- Working with paths longer than 3-4 hops
- Complex pattern matching requirements
- 优化可变长度路径查询
- 需要在遍历过程中尽早过滤
- 处理超过3-4跳的路径
- 复杂模式匹配需求
Query Generation Checklist
查询生成检查清单
Before finalizing any generated query:
- ✅ No deprecated functions (id, btree indexes, etc.)
- ✅ Explicit grouping for aggregations
- ✅ NULL filters for all sorted properties
- ✅ Appropriate subquery patterns for reads
- ✅ Consider QPP for paths with filtering needs
- ✅ Use COUNT{} instead of size() for pattern counting
- ✅ Variable scope clauses in CALL subqueries
- ✅ Unique variable names for relationships
在最终确定任何生成的查询前:
- ✅ 无废弃函数(id、btree索引等)
- ✅ 聚合操作使用显式分组
- ✅ 所有排序属性均有NULL过滤
- ✅ 为读取操作使用合适的子查询模式
- ✅ 对有过滤需求的路径考虑使用QPP
- ✅ 模式计数使用COUNT{}而非size()
- ✅ CALL子查询中使用变量作用域子句
- ✅ 关系使用唯一变量名
Error Resolution Patterns
错误解决模式
"Implicit grouping key" errors
"隐式分组键"错误
cypher
// Problem: RETURN n.prop, count(*) + n.other
// Solution: WITH n.prop AS prop, n.other AS other, count(*) AS cnt
// RETURN prop, cnt + othercypher
// Problem: RETURN n.prop, count(*) + n.other
// Solution: WITH n.prop AS prop, n.other AS other, count(*) AS cnt
// RETURN prop, cnt + other"id() function not found"
"id()函数未找到"
cypher
// Use elementId() but note it returns a string, not integercypher
// Use elementId() but note it returns a string, not integer"Repeated variable" errors
"重复变量"错误
cypher
// Problem: MATCH (a)-[r*]->(), (b)-[r*]->()
// Solution: MATCH (a)-[r1*]->(), (b)-[r2*]->()cypher
// Problem: MATCH (a)-[r*]->(), (b)-[r*]->()
// Solution: MATCH (a)-[r1*]->(), (b)-[r2*]->()Performance Tips
性能技巧
- Start with indexed properties - Always anchor patterns with indexed lookups
- Filter early in QPP - Apply WHERE clauses within the pattern
- Filter nulls before sorting - Prevent unexpected results and improve performance
- Limit expansion depth - Use reasonable upper bounds in quantifiers
- Use EXISTS for existence checks - More efficient than counting
- Profile queries - Use PROFILE to identify bottlenecks
- 从索引属性开始 - 始终使用索引查找作为模式的锚点
- 在QPP中尽早过滤 - 在模式内应用WHERE子句
- 排序前过滤空值 - 避免意外结果并提升性能
- 限制扩展深度 - 在量词中使用合理的上限
- 使用EXISTS进行存在性检查 - 比计数更高效
- 分析查询 - 使用PROFILE识别瓶颈
Modern Cypher Features
现代Cypher特性
Label Expressions
标签表达式
cypher
WHERE n:Label1|Label2 // OR
WHERE n:Label1&Label2 // AND
WHERE n:!Archived // NOTcypher
WHERE n:Label1|Label2 // OR
WHERE n:Label1&Label2 // AND
WHERE n:!Archived // NOTType Predicates
类型断言
cypher
WHERE n.prop IS :: STRING
WHERE n.value IS :: INTEGER NOT NULL
WHERE n.data IS :: LIST<STRING>cypher
WHERE n.prop IS :: STRING
WHERE n.value IS :: INTEGER NOT NULL
WHERE n.data IS :: LIST<STRING>Subquery Patterns for Reads
读取操作的子查询模式
- COUNT{} - Count patterns efficiently
- EXISTS{} - Check pattern existence
- COLLECT{} - Collect complex results
- CALL{} - Execute subqueries for complex reads
- COUNT{} - 高效计数模式
- EXISTS{} - 检查模式存在性
- COLLECT{} - 收集复杂结果
- CALL{} - 执行子查询以处理复杂读取
Quantified Path Patterns
量化路径模式
- Inline filtering during traversal
- Access to nodes and relationships in patterns
- Significant performance improvements (up to 1000x)
- Support for complex, multi-hop patterns
Always prefer modern syntax patterns for better performance and maintainability.
- 遍历过程中内联过滤
- 可访问模式中的节点和关系
- 性能显著提升(最高可达1000倍)
- 支持复杂的多跳模式
为了获得更好的性能和可维护性,请始终优先使用现代语法模式。