opsmill/infrahub / .agents/skills/neo4j-cypher-guide
neo4j-cypher-guide
VerifiedComprehensive guide for writing modern Neo4j Cypher queries. Essential for text2cypher MCP tools and LLMs generating Cypher queries. Covers removed/deprecated syntax, modern replacements, CALL subqueries for reads, COLLECT patterns, sorting best practices, set-based writes, Quantified Path Patterns (QPP) for efficient graph traversal, and how to choose the entry point of a query so the plan starts with an index seek instead of a label scan.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 9.6 KB |
| references/deprecated-syntax.md | markdown | 2.7 KB |
| references/entry-points.md | markdown | 3.6 KB |
| references/qpp.md | markdown | 6.5 KB |
| references/subqueries.md | markdown | 4.4 KB |
references/subqueries.md
View on GitHub# Neo4j Subqueries and Aggregation Patterns
## CALL Subqueries for Read Operations
### Basic Syntax
CALL subqueries allow for complex query composition for:
- Post-union processing
- Limiting results per row
- Conditional queries
- Complex aggregations
### Variable Scope Clause (Recommended)
```cypher
// Import specific variables
MATCH (p:Person)
CALL (p) {
MATCH (p)-[:KNOWS]->(friend)
RETURN friend
}
RETURN p, friend
// Import no variables
MATCH (p:Person)
CALL () {
MATCH (c:Company)
RETURN count(c) AS companyCount
}
RETURN p, companyCount
```
### Conditional Queries
```cypher
// Return different results based on conditions
MATCH (n:Node)
CALL (n) {
WITH n
WHERE n.type = 'A'
RETURN 'TypeA' AS result, n.propertyA AS value
UNION
WITH n
WHERE n.type = 'B'
RETURN 'TypeB' AS result, n.propertyB AS value
}
RETURN n.id, result, value
```
### Post-UNION Processing
```cypher
CALL {
MATCH (p:Person) RETURN p AS node, 'Person' AS type
UNION
MATCH (c:Company) RETURN c AS node, 'Company' AS type
}
WITH node, type
WHERE node.revenue > 1000000
RETURN node.name, type
```
## COLLECT Subqueries
### Basic COLLECT Subquery
```cypher
MATCH (p:Person)
WITH p, COLLECT {
MATCH (p)-[:KNOWS]->(friend)
RETURN friend.name
} AS friendNames
RETURN p.name, friendNames
```
### Complex COLLECT with Filtering
```cypher
MATCH (p:Person)
WITH p, COLLECT {
MATCH (p)-[:KNOWS]->(f)
WHERE f.age > 30
WITH f
ORDER BY f.age DESC
LIMIT 5
RETURN f.name
} AS topOldestFriends
RETURN p.name, topOldestFriends
```
## COUNT Subqueries
### Modern count{} syntax
```cypher
// Count relationships
MATCH (p:Person)
WHERE count{(p)-[:KNOWS]->()} > 5
RETURN p
// Using COUNT in RETURN
MATCH (p:Person)
RETURN p.name, count{(p)-[:KNOWS]->()} AS friendCount
ORDER BY friendCount DESC
```
## EXISTS Subqueries
### Pattern Existence Check
```cypher
// Simple pattern check
MATCH (p:Person)
WHERE EXISTS {(p)-[:MANAGES]->(:Department)}
RETURN p
// Complex existence check
MATCH (p:Person)
WHERE EXISTS {
MATCH (p)-[:WORKS_IN]->(d:Department)
WHERE d.budget > 1000000
}
RETURN p
```
## Sorting Best Practices
### IMPORTANT: Always Filter NULL Values When Sorting
```cypher
// WRONG - May include null values in results
MATCH (p:Person)
RETURN p.name, p.age
ORDER BY p.age
// CORRECT - Filter out null values before sorting
MATCH (p:Person)
WHERE p.age IS NOT NULL
RETURN p.name, p.age
ORDER BY p.age
// Alternative - Handle nulls explicitly
MATCH (p:Person)
RETURN p.name, p.age
ORDER BY p.age DESC NULLS LAST
```
## Aggregation Best Practices
### Avoiding Implicit Grouping Keys
```cypher
// WRONG - Will fail in modern Neo4j
MATCH (p:Person)
RETURN p.name, p.age + count(*)
// CORRECT - Explicit grouping
MATCH (p:Person)
WITH p.name AS name, p.age AS age, count(*) AS cnt
RETURN name, age + cnt
```
### Proper Use of COLLECT
```cypher
// Collecting with ordering
MATCH (d:Department)<-[:WORKS_IN]-(p:Person)
WHERE p.salary IS NOT NULL // Filter nulls before sorting
WITH d, p ORDER BY p.salary DESC
RETURN d.name, collect(p.name)[..5] AS topEarners
```
### Memory-Efficient Aggregations
```cypher
// Use subqueries to limit aggregation scope
MATCH (d:Department)
CALL (d) {
MATCH (d)<-[:WORKS_IN]-(p:Person)
WHERE p.salary IS NOT NULL
RETURN avg(p.salary) AS avgSalary
}
RETURN d.name, avgSalary
```
## Common Read Patterns
### Pattern: Get Top N per Group
```cypher
MATCH (d:Department)
CALL (d) {
MATCH (d)<-[:WORKS_IN]-(p:Person)
WHERE p.salary IS NOT NULL // Always filter nulls when sorting
WITH p ORDER BY p.salary DESC
LIMIT 3
RETURN collect(p.name) AS topThree
}
RETURN d.name, topThree
```
### Pattern: Conditional Aggregation
```cypher
MATCH (p:Person)
WITH p,
count{(p)-[:KNOWS]->(:Person)} AS friendCount,
count{(p)-[:WORKS_WITH]->(:Person)} AS colleagueCount
WHERE friendCount > colleagueCount
RETURN p.name, friendCount, colleagueCount
```
### Pattern: Multiple Aggregations
```cypher
MATCH (c:Company)
CALL (c) {
MATCH (c)<-[:WORKS_FOR]-(p:Person)
WHERE p.age IS NOT NULL // Filter nulls for accurate aggregation
RETURN count(p) AS employees, avg(p.age) AS avgAge
}
RETURN c.name, employees, avgAge
```
### Pattern: Limiting Results per Row
```cypher
// Get first 3 friends for each person
MATCH (p:Person)
CALL (p) {
MATCH (p)-[:KNOWS]->(friend)
RETURN friend
ORDER BY friend.name
LIMIT 3
}
RETURN p.name, collect(friend.name) AS firstThreeFriends
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |