Appearance
Neo4j Cypher Optimization
Use Indexes for Node Lookups
Dữ liệu mẫu và index (chạy một lần trên neo4j:5, heap ≥ 1 GB; các ví dụ trong mục này dùng chung; số đo trong mục lấy từ 100 000 User, Neo4j 5.26):
cypher
CREATE INDEX user_id_idx IF NOT EXISTS FOR (n:User) ON (n.id);
CREATE INDEX user_email_idx IF NOT EXISTS FOR (n:User) ON (n.email);
CREATE INDEX user_created_idx IF NOT EXISTS FOR (n:User) ON (n.createdAt);
CREATE INDEX prod_id_idx IF NOT EXISTS FOR (n:Product) ON (n.id);
CREATE INDEX prod_cat_idx IF NOT EXISTS FOR (n:Product) ON (n.category);
CALL { UNWIND range(1,100000) AS i CREATE (:User {id:i, name:'user'+i, email:'u'+i+'@example.com', createdAt:i, flagged:(i%1000=0)}) } IN TRANSACTIONS OF 10000 ROWS;
CALL { UNWIND range(1,1000) AS i CREATE (:Product {id:i, name:'product'+i, price:i, category:'c'+(i%20)}) } IN TRANSACTIONS OF 1000 ROWS;
CREATE (:User {id:0, name:'John', email:'john@example.com', createdAt:0});
// Mỗi User theo dõi 10 User khác; User 7 theo dõi thêm 20 000 User (supernode)
UNWIND range(1,100000) AS i CALL { WITH i MATCH (a:User {id:i}) UNWIND range(1,10) AS k MATCH (b:User {id:(i*7+k*13)%100000+1}) CREATE (a)-[:FOLLOWS]->(b) } IN TRANSACTIONS OF 2000 ROWS;
UNWIND range(1,20000) AS k CALL { WITH k MATCH (a:User {id:7}), (b:User {id:k+10}) MERGE (a)-[:FOLLOWS]->(b) } IN TRANSACTIONS OF 2000 ROWS;
UNWIND range(1,100000) AS i CALL { WITH i MATCH (a:User {id:i}) UNWIND range(1,3) AS k MATCH (p:Product {id:(i*k)%1000+1}) MERGE (a)-[:PURCHASED]->(p) } IN TRANSACTIONS OF 2000 ROWS;
UNWIND range(1,100000) AS i CALL { WITH i MATCH (a:User {id:i}) UNWIND range(1,3) AS k MATCH (b:User {id:(i*11+k*17)%100000+1}) CREATE (a)-[:TRANSACTED {amount: (i*k)%500}]->(b) } IN TRANSACTIONS OF 2000 ROWS;
MATCH (j:User {email:'john@example.com'}), (p:Product) WHERE p.id IN [6,11,16] CREATE (j)-[:PURCHASED]->(p);
CALL db.awaitIndexes(300);Query with index:
cypher
// ✅ Uses index (fast)
MATCH (u:User {email: 'john@example.com'})
RETURN u
// ❌ No index (scans all User nodes)
MATCH (u:User)
WHERE u.name = 'John' // No index on name
RETURN uCheck if index is used:
cypher
EXPLAIN MATCH (u:User {email: 'john@example.com'}) RETURN u;
// Tìm NodeIndexSeek (tốt); NodeByLabelScan + Filter nghĩa là chưa dùng index
PROFILE MATCH (u:User {email: 'john@example.com'}) RETURN u;
// Chạy thật, in số liệu từng bước; đo: 6 db hits
// Không có index trên name: MATCH (u:User) WHERE u.name = 'John' RETURN u quét NodeByLabelScan, 200 008 db hitsPROFILE vs EXPLAIN
EXPLAIN (dry run, no execution):
cypher
EXPLAIN MATCH (u:User)-[:FOLLOWS]->(f:User) RETURN f.name
// Shows query plan (what Neo4j WILL do)PROFILE (actual execution, with stats):
cypher
PROFILE MATCH (u:User)-[:FOLLOWS]->(f:User) RETURN f.name
// Shows actual rows processed, db hitsKey metrics:
db hits- Number of operations (lower = better)rows- Rows processed at each step- Look for
NodeIndexSeek(index used)
Avoid Cartesian Products
❌ Bad: Missing relationship (Cartesian product)
cypher
MATCH (u:User), (p:Product)
WHERE u.id = 123
RETURN p
// Returns user 123 × ALL products (every product, unrelated to the user)✅ Good: Use relationship
cypher
MATCH (u:User {id: 123})-[:PURCHASED]->(p:Product)
RETURN p
// Only products purchased by user 123Start with Most Selective Match
Viết bắt đầu từ Product (đảo chiều):
cypher
MATCH (p:Product)<-[:PURCHASED]-(u:User)
WHERE u.email = 'john@example.com'
RETURN p;
// Planner theo chi phí vẫn bắt đầu từ NodeIndexSeek trên User(email); đo: 24 db hitsViết bắt đầu từ User:
cypher
MATCH (u:User {email: 'john@example.com'})-[:PURCHASED]->(p:Product)
RETURN p;
// Cùng plan, cùng 24 db hits. Thứ tự viết không quyết định plan; index trên điểm bắt đầu mới quyết định. Kiểm bằng PROFILEUse LIMIT to Stop Early
❌ Bad: Process all, then limit
cypher
// Không có điểm bắt đầu: quét mọi User, sắp xếp rồi mới lấy 10
MATCH (u:User)-[:FOLLOWS]->(f:User)
RETURN f.name
ORDER BY f.createdAt DESC
LIMIT 10;
// Đo: 200 027 db hits (NodeByLabelScan + Top)✅ Good: Bắt đầu từ một node cụ thể
cypher
MATCH (u:User {id: 7})-[:FOLLOWS]->(f:User)
RETURN f.name
ORDER BY f.createdAt DESC
LIMIT 10;
// Đo: 60 015 db hits. Top chỉ giữ 10 hàng nhưng vẫn đọc cả 20 000 node u theo dõi: ORDER BY phải thấy hết hàng trước khi trả hàng đầu tiên✅ Dừng sớm thật: ORDER BY + LIMIT trên thuộc tính có index
cypher
MATCH (f:User)
WHERE f.createdAt IS NOT NULL
RETURN f.name
ORDER BY f.createdAt DESC
LIMIT 10;
// Đo: 21 db hits (NodeIndexScan 11 + Projection 10)
// Bỏ dòng WHERE ... IS NOT NULL thì planner không dùng thứ tự index: 200 013 db hitsAvoid Dense Supernodes
Problem: Node with millions of relationships (slow traversal)
Example:
cypher
// ❌ Bad: "All Users" node with 10M relationships
(:AllUsers)-[:MEMBER]->(:User)
// Traversing AllUsers node scans 10M relationshipsSolution: Use labels instead
cypher
// ✅ Good: Label-based lookup
MATCH (u:User) RETURN u
// NodeByLabelScan: đọc từng User qua label scan, không đi qua quan hệ MEMBER; vẫn đọc mọi User, nên thêm điều kiện trên thuộc tính có index nếu chỉ cần một phầnWAR STORIES: Neo4j Production Incidents
War Story 1: The Supernode That Brought Down Friend Recommendations
Kịch bản minh hoạ, không phải sự cố có nguồn: số liệu, đơn giá và thời gian trong câu chuyện là ví dụ.
Context:
- Social network with 2M users
- Neo4j 4.3 on 32GB RAM, 8 CPU
- Friend recommendation feature launched
The Incident (Day 7 after launch):
Timeline:
09:00 - Recommendation queries start timing out (30s+)
09:15 - P50 latency: 2,400ms (target: 100ms)
09:30 - Heap usage: 28GB/32GB (normal: 12GB)
09:45 - GC pauses: 8-15 seconds every minute
10:00 - Service down (OOM kills Neo4j)
Cypher query:
MATCH (u:User {id: $userId})-[:FOLLOWS]->(f:User)-[:FOLLOWS]->(rec:User)
WHERE NOT (u)-[:FOLLOWS]->(rec)
RETURN rec.name, count(*) as mutualFriends
ORDER BY mutualFriends DESC
LIMIT 10Root Cause Analysis:
cypher
// Investigation (Neo4j 4.3; trên 5.x thay size(pattern) bằng COUNT { (u)-[:FOLLOWS]->() } AS followCount):
MATCH (u:User)
WITH u, size((u)-[:FOLLOWS]->()) as followCount
WHERE followCount > 10000
RETURN u.id, followCount
ORDER BY followCount DESC
LIMIT 5
// Results:
| u.id | followCount |
|-----------|-------------|
| celebrity1| 847,234 | ← Supernode!
| celebrity2| 523,891 |
| celebrity3| 412,556 |
| brand1 | 358,229 |
| brand2 | 287,445 |
// Problem:
// When user follows celebrity1 (847K relationships):
// - Query loads 847K relationships into memory
// - Then traverses EACH relationship for 2nd hop
// - Total relationships processed: 847K × avg(200) = 169M relationships!
// - Memory per query: ~4GB
// - 8 concurrent queries = 32GB (OOM)The Fix:
cypher
// ❌ WRONG: Traverses supernodes
MATCH (u:User {id: $userId})-[:FOLLOWS]->(f:User)-[:FOLLOWS]->(rec:User)
WHERE NOT (u)-[:FOLLOWS]->(rec)
RETURN rec.name, count(*) as mutualFriends
// ✓ CORRECT: Filter out supernodes early
MATCH (u:User {id: $userId})-[:FOLLOWS]->(f:User)
WHERE COUNT { (f)-[:FOLLOWS]->() } < 10000 // Skip supernodes
WITH u, f
MATCH (f)-[:FOLLOWS]->(rec:User)
WHERE NOT (u)-[:FOLLOWS]->(rec)
AND COUNT { (rec)-[:FOLLOWS]->() } < 10000 // Skip supernode recommendations
RETURN rec.name, count(*) as mutualFriends
ORDER BY mutualFriends DESC
LIMIT 10
// Performance improvement:
// Before: 2,400ms avg, 28GB heap, 8s GC pauses
// After: 47ms avg, 14GB heap, <100ms GC pauses (51x faster!)Cost Impact:
Downtime:
- 3.5 hours outage
- Revenue loss: $18,000 (e-commerce conversion impact)
Infrastructure:
- Emergency scaling: 32GB → 64GB RAM × 3 nodes
- Monthly cost increase: $840/month → $1,680/month
Engineering:
- 2 engineers × 16 hours debugging = $4,800Key Lessons:
- Profile queries before launch:
PROFILEwould've shown 169M relationship traversals - Limit relationship degrees: Tránh duyệt qua supernode khi không cần (ngưỡng 10K là ví dụ; đo phân phối bậc của dữ liệu mình)
- Monitor relationship distribution: Alert khi bậc vượt ngưỡng đã đo (5K là ví dụ)
- Lưu bậc thành thuộc tính khi cần lọc nhanh: ví dụ
followCountcó index; tính bằngCOUNT { }cho từng node tốn thêm db hits
Detection:
cypher
// Find supernodes (chạy ngoài giờ cao điểm: MATCH (n) quét mọi node, đo 303 004 db hits trên 101 001 node)
MATCH (n)
WITH labels(n)[0] AS label, n, COUNT { (n)--() } AS degree
WHERE degree > 10000
RETURN label, elementId(n) AS nodeId, degree
ORDER BY degree DESC
LIMIT 100Bài học: một node có hàng trăm nghìn quan hệ làm mọi truy vấn hai bước đi qua nó phình theo bậc; đo phân phối bậc bằng PROFILE và lọc hoặc lưu bậc trước khi ra production.
War Story 2: The 3-Hop Traversal That Cost $47K in Compute
Kịch bản minh hoạ, không phải sự cố có nguồn: số liệu, đơn giá và thời gian trong câu chuyện là ví dụ. Đơn giá CPU-giờ và hoá đơn không lấy từ bảng giá thật.
Context:
- Fraud detection system on Neo4j 4.4 Enterprise
- Neo4j AuraDB Professional: 96GB RAM, 24 CPU
- Cost: $3,920/month base + compute overage
The Incident (Q4 2024 - Black Friday week):
Timeline:
Nov 25 - Black Friday traffic surge (10x normal)
Nov 26 - Fraud detection queries timing out (45s+)
Nov 27 - AuraDB compute usage: 847 CPU-hours (normal: 180/month)
Nov 28 - Invoice alert: ~$47K overage charge!
Cypher query (fraud ring detection):
MATCH path = (u1:User)-[:TRANSACTED*1..3]-(u2:User)
WHERE u1.id = $suspiciousUserId
AND u2.flagged = true
RETURN pathRoot Cause Analysis:
cypher
// Investigation with PROFILE:
PROFILE MATCH path = (u1:User {id: 12345})-[:TRANSACTED*1..3]-(u2:User)
WHERE u2.flagged = true
RETURN path
// Kết quả minh hoạ (trên 5.x toán tử tên VarLengthExpand(All); xem PROFILE thật):
+----------------------+-------+--------+
| Operator | Rows | DbHits |
+----------------------+-------+--------+
| ProduceResults | 847 | 0 |
| Filter (flagged) | 847 | 2.3M | ← Problem!
| VarLengthExpand(1,3) | 2.3M | 18.7M | ← Disaster!
| NodeIndexSeek | 1 | 2 |
+----------------------+-------+--------+
// Explosion calculation:
// - User 12345 has 52 transactions (degree 52)
// - Avg user has 23 transactions
// - 1-hop: 52 nodes
// - 2-hop: 52 × 23 = 1,196 nodes
// - 3-hop: 1,196 × 23 = 27,508 nodes
// - Total: 28,756 nodes (× 80 thuộc tính ≈ 2.3M db hits, khớp dòng Filter ở bảng trên)
// Black Friday impact:
// - 12,500 fraud checks/day (vs normal 1,200)
// - 28,756 nodes per query
// - Total nodes processed: 359M nodes/day
// - Compute time: 28.9 CPU-hours/day × 5 days = 144.5 CPU-hours
// - Overage: 144.5 × $327/CPU-hour ≈ $47,251 (~$47K)The Fix:
cypher
// ❌ WRONG: Unbounded 3-hop traversal
MATCH path = (u1:User)-[:TRANSACTED*1..3]-(u2:User)
WHERE u1.id = $suspiciousUserId
AND u2.flagged = true
RETURN path
// ✓ CORRECT: Điểm bắt đầu có index, giới hạn độ dài và lọc cạnh sớm
MATCH path = (u1:User {id: $suspiciousUserId})-[:TRANSACTED*1..2]-(u2:User)
WHERE u2.flagged = true
AND ALL(r IN relationships(path) WHERE r.amount > 100) // Lọc cạnh ngay trong VarLengthExpand
RETURN path
LIMIT 50 // Giới hạn kết quả
// Performance improvement:
// Before: 45,000ms, 28,756 nodes, 18.7M db hits
// After: 340ms, 267 nodes, 12,400 db hits (132x faster!)
// Cost savings:
// - Compute: 144.5 → 2.1 CPU-hours/day during surge
// - Overage: $47K → $0 (within base quota)Additional optimization - Precompute flagged network:
cypher
// Batch job (chạy hằng ngày, ngoài giờ cao điểm), mỗi lô 1000 User một giao dịch:
// Tạo quan hệ "CONNECTED_TO_FLAGGED" để tra nhanh
MATCH (u1:User)
CALL {
WITH u1
MATCH path = (u1)-[:TRANSACTED*1..2]-(u2:User)
WHERE u2.flagged = true
WITH u1, u2, min(length(path)) AS hops
MERGE (u1)-[r:CONNECTED_TO_FLAGGED]->(u2)
SET r.hops = hops,
r.lastChecked = datetime()
} IN TRANSACTIONS OF 1000 ROWS;
// Real-time query (10x faster):
MATCH (u1:User {id: $suspiciousUserId})-[r:CONNECTED_TO_FLAGGED]->(u2:User)
RETURN u2, r.hops
// 340ms → 28ms (12x faster than optimized version)Cost Impact:
Immediate:
- Overage charge: ~$47K (Black Friday week)
- Emergency optimization: 2 engineers × 18 hours = $5,400
Ongoing:
- Prevented future overages: ~$18K/month during peak seasons
- Monthly savings: $216K/yearKey Lessons:
- Variable-length paths are expensive: Each hop multiplies node count exponentially
- Always LIMIT variable-length expansion: Use
*1..2not*1..3, addLIMIT - Precompute expensive traversals: Batch jobs for fraud rings, recommendations
- Monitor compute in serverless: Set budget alerts on AuraDB compute usage
Detection:
cypher
// Tìm query var-length tốn kém bằng query.log (neo4j.conf, Neo4j 5.x), mỗi thiết lập một dòng riêng trong file:
// db.logs.query.enabled=INFO
// db.logs.query.threshold=1s
// db.logs.query.plan_description_enabled=true
// Rồi tìm VarLengthExpand trong query.log
// Real-time monitoring:
SHOW TRANSACTIONS YIELD transactionId, currentQuery, elapsedTime, currentQueryAllocatedBytes
WHERE elapsedTime.milliseconds > 5000 // 5+ seconds
AND currentQuery CONTAINS '*' // Variable-length pattern
RETURN transactionId, currentQuery, elapsedTime, currentQueryAllocatedBytes
ORDER BY elapsedTime DESCBài học: đường var-length không cận và không điểm bắt đầu có index là chi phí bùng nổ theo cấp số nhân; giới hạn độ dài, lọc cạnh sớm, đặt cảnh báo ngân sách.
War Story 3: The Cartesian Product That Scanned 847M Relationships
Kịch bản minh hoạ, không phải sự cố có nguồn: số liệu, đơn giá và thời gian trong câu chuyện là ví dụ.
Context:
- E-commerce recommendation engine on Neo4j 4.4
- Dataset: 2.8M users, 12M products, 89M purchases
- Neo4j cluster: 3 core servers (64GB RAM each)
The Incident (Product launch - December 2024):
Timeline:
Dec 10 - New "Customers also bought" feature deployed
Dec 10 09:30 - P95 latency spikes: 180ms → 37,000ms
Dec 10 09:45 - CPU usage: 95%+ on all 3 core servers
Dec 10 10:00 - Heap usage: 58GB/64GB per server
Dec 10 10:15 - Query queue: 3,200 queries (normal: <50)
Dec 10 10:30 - Emergency rollback
Cypher query:
MATCH (u:User), (p:Product)
WHERE u.id = $userId
AND p.category = $category
AND EXISTS((u)-[:PURCHASED]->(p))
RETURN p.name, p.price
LIMIT 10Root Cause Analysis:
cypher
// Investigation with EXPLAIN:
EXPLAIN MATCH (u:User), (p:Product)
WHERE u.id = $userId
AND p.category = $category
AND EXISTS((u)-[:PURCHASED]->(p))
RETURN p.name
// Kết quả minh hoạ, giả định CHƯA có index trên User(id). Với index User(id) planner dùng NodeIndexSeek rồi CartesianProduct (1 User × các Product cùng category) + SemiApply, không quét mọi User (đo trên neo4j:5.26):
// Query plan:
+---------------------------+-----------+
| Operator | EstRows |
+---------------------------+-----------+
| Limit | 10 |
| Filter (EXISTS) | 142 | ← Too late!
| CartesianProduct | 33.6M | ← Disaster!
| - NodeByLabelScan(:User) | 2.8M |
| - Filter(category) | 12 |
| - NodeByLabelScan(:Prod)| 12M |
+---------------------------+-----------+
// Cartesian explosion:
// - 2.8M users × 12 products (after category filter) = 33.6M combinations
// - For EACH combination, check if relationship EXISTS
// - Total relationship checks: 33.6M
// - With 89M relationships total, avg scan per query: ~420M operations
// - 250 concurrent queries: 105 BILLION operations
// Performance breakdown:
PROFILE MATCH (u:User), (p:Product)
WHERE u.id = $userId AND p.category = $category
AND EXISTS((u)-[:PURCHASED]->(p))
RETURN p.name LIMIT 10
// Actual stats:
// - db hits: 847,234,891 (847M!)
// - rows: 33,600,000 (33.6M cartesian product)
// - time: 37,234ms
// - memory: 4.2GB per queryThe Fix:
cypher
// ❌ WRONG: Cartesian product (missing relationship in MATCH)
MATCH (u:User), (p:Product)
WHERE u.id = $userId
AND p.category = $category
AND EXISTS((u)-[:PURCHASED]->(p))
RETURN p.name, p.price
// Problem: MATCH creates cartesian product, then EXISTS filters
// ✓ CORRECT: Use relationship in MATCH
MATCH (u:User {id: $userId})-[:PURCHASED]->(p:Product {category: $category})
RETURN p.name, p.price
LIMIT 10
// Performance improvement:
// Before: 37,234ms, 847M db hits, 33.6M rows
// After: 12ms, 47 db hits, 8 rows (3,103x faster!)
// Even better: Add index on category
CREATE INDEX prod_cat_idx IF NOT EXISTS FOR (n:Product) ON (n.category);
// After index: 8ms, 24 db hits, 8 rows (4,654x faster!)Cost Impact:
Revenue:
- 45 minutes downtime during peak shopping hours
- Conversion rate drop: 12.7% → 3.2% (rollback in progress)
- Estimated revenue loss: $127,000
Infrastructure:
- Emergency scaling: 64GB → 128GB RAM × 3 nodes (during incident)
- Emergency compute cost: $2,340 (overprovisioning during fix)
Engineering:
- Hotfix deployment: 3 engineers × 8 hours = $7,200
- Post-mortem and testing: 5 engineers × 6 hours = $9,000Detection Strategy:
cypher
// Detect cartesian products in query plans:
// 1. Look for "CartesianProduct" operator in EXPLAIN/PROFILE
// 2. Monitor queries with high db hits:
SHOW TRANSACTIONS YIELD transactionId, currentQuery, elapsedTime
WHERE elapsedTime.milliseconds > 1000
RETURN transactionId, currentQuery, elapsedTime
// 3. Static analysis (code review):
// Flag queries with multiple MATCH clauses without relationships:
MATCH (a:Label1), (b:Label2) // ⚠️ Red flag!
WHERE ...Key Lessons:
- Use relationships in MATCH: viết
MATCH (a)-[r]->(b)khi hai node có liên hệ;MATCH (a), (b)tạo CartesianProduct - Đo EXISTS bằng PROFILE: với index trên
User(id), planner chạy EXISTS thành SemiApply sau CartesianProduct nhỏ (đo); đưa quan hệ vào MATCH vẫn gọn hơn - EXPLAIN before production: Check for CartesianProduct operator
- Index thuộc tính dùng để lọc: index trên
categorycho phép planner dùng NodeIndexSeek thay vì quét theo nhãn; mức giảm db hits đo bằng PROFILE trên dữ liệu của bạn
Rule of thumb:
cypher
// ❌ Anti-pattern (triggers cartesian product):
MATCH (a:Label1), (b:Label2)
WHERE condition
// ✅ Correct pattern (uses relationship):
MATCH (a:Label1)-[r:REL_TYPE]->(b:Label2)
WHERE conditionBài học: hai MATCH rời nhau tạo CartesianProduct; đưa quan hệ vào MATCH, đọc EXPLAIN tìm toán tử CartesianProduct trước khi đưa lên production.
Phải nhớ:
- Đọc plan trước khi tối ưu:
PROFILEcho NodeIndexSeek hay NodeByLabelScan, có CartesianProduct không, db hits bao nhiêu; thứ tự viết không đổi plan, index và pattern mới đổi. - Chặn bùng nổ: đường var-length có cận trên nhỏ và điểm bắt đầu có index; lọc supernode bằng
COUNT { }; ghi hàng loạt bằngCALL { ... } IN TRANSACTIONS OF n ROWS. - Số liệu war story là minh hoạ; Neo4j 5.x:
size(pattern)báo lỗi (dùngCOUNT { }),id()đổi thànhelementId().