The Complete Production SOP: How to Deploy and Run Neo4j Cypher Graph Queries & Index Tuning in Autonomous AI Agents
Production SOP to install and run Neo4j Cypher graph query optimization in Codex, Claude Code, and Cursor. Fix Cartesian products and tune indexes.
Technical Overview & Architectural Context
Autonomous coding agents frequently generate unoptimized Neo4j Cypher queries that trigger catastrophic Cartesian products, unindexed node scans, and memory bloat on large-scale property graphs. When untrained LLMs attempt variable-length pattern matches (such as `MATCH (a)-[*]->(b)` without bound labels or depth limits), the search space explodes exponentially, causing query timeouts and cluster CPU saturation. Without deterministic boundaries, agents also routinely produce unparameterized Cypher strings vulnerable to injection and plan-cache invalidation, while neglecting schema indexing (`RANGE`, `TEXT`, and `POINT` indexes). The `neo4j-cypher-graph-query-opt` skill solves this by enforcing strict procedural guidelines: parameterizing all dynamic literals, requiring index backed anchor nodes, verifying execution plans using `EXPLAIN` and `PROFILE`, and mandating APOC procedures for batched mutations.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Manifest Mounting and Agent Rule Injection
Create the local skill manifest directory and inject verified procedural rules into the agent runtime.
Agent runtimes such as Claude Code, Cursor, and Codex automatically scan directory structures for SKILL.md configurations. By placing the manifest in `.claude/skills/` or the global `~/.agents/skills/` directory, the runtime matches user prompt triggers with the Cypher optimization SOP.
mkdir -p .agents/skills/neo4j-cypher-graph-query-opt && curl -fsSL https://askills.dev/api/skills/neo4j-cypher-graph-query-opt/raw -o .agents/skills/neo4j-cypher-graph-query-opt/SKILL.md---
name: "neo4j-cypher-graph-query-opt"
description: "Traverse complex relationships and network topologies in sub-milliseconds using Neo4j Cypher."
metadata:
author: "Neo4j"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "write cypher graph query"
- "optimize neo4j cypher query"
- "create neo4j relationship index"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---Keep the runtime permission `shell_exec: false` to force the agent to produce validated `.cypher` scripts rather than executing untracked direct mutations against your database.
Ensure the directory name matches the skill slug exactly; discrepancies can cause Claude Code or Windsurf to bypass trigger matching.
Schema Definition & Index Alignment
Instruct the agent to establish range, point, and text indexes before composing traversal logic.
Optimal graph traversals require high-cardinality anchor points. The agent must verify existing schema indexes using `SHOW INDEXES` and generate schema definitions that prevent all-node scans.
cat << 'EOF' > schema/indexes.cypher
CREATE CONSTRAINT unique_user_id IF NOT EXISTS
FOR (u:User) REQUIRE u.id IS UNIQUE;
CREATE INDEX user_email_idx IF NOT EXISTS
FOR (u:User) ON (u.email);
CREATE INDEX rel_purchased_date_idx IF NOT EXISTS
FOR ()-[r:PURCHASED]-() ON (r.timestamp);
EOFMandate relationship property indexes for temporal graph queries to prune expansion edges before node state checks.
Creating fulltext or point indexes in Neo4j 5.x uses updated syntax (`CREATE FULLTEXT INDEX`); avoid obsolete Neo4j 4.x `CALL db.index.fulltext.createNodeIndex` syntax.
Parameterized Query Composition & Trigger Invocation
Invoke the skill using explicit triggers to generate fully parameterized Cypher templates.
When invoking triggers like 'optimize neo4j cypher query', the agent loads the SOP rules: enforcing bound path expansion, avoiding optional matches before early filtering, and isolating subqueries with `CALL { ... }` blocks.
Explicitly include target latency constraints in your prompt (e.g., '<10ms traversal over 4 hops') to trigger `CALL apoc.path.expandConfig` usage.
Plan Profiling & Quality Gate Verification
Validate query performance metrics using PROFILE and EXPLAIN syntax checks before commiting.
The skill mandates that the agent wrap candidate queries in `EXPLAIN` or `PROFILE` commands to evaluate operator pipes. The quality gate fails if any CartesianProduct operator appears in the execution plan.
cypher-shell -a ${NEO4J_URI:-bolt://localhost:7687} -u ${NEO4J_USER:-neo4j} -p ${NEO4J_PASSWORD:-password} < schema/indexes.cypherCheck dbHits in the returned PROFILE table: healthy queries maintain dbHits roughly proportional to the returned subgraph rather than total graph node count.
Real-World Scenario: Sub-millisecond Multi-Hop Fraud Ring Traversal Query
“write cypher graph query to detect circular transaction loops where an Account sends funds through 2 to 4 intermediary Accounts back to the originating User within 24 hours, optimized for a graph of 50M transactions.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent attempted a query with disconnected MATCH clauses or an unbounded variable-length path pattern with embedded inline property filters like `[:REL*1..3 {status: 'active'}]` which Neo4j rejects or converts into Cartesian products.
MATCH (a:Account {id: $id})
MATCH (b:Account {id: $targetId})
MATCH path = (a)-[:TRANSFER*1..3]->(b)
WHERE all(r IN relationships(path) WHERE r.status = 'active')
RETURN path;Root Cause: Eager operators caused by unpipelined aggregations or collecting massive subgraphs into memory prior to filtering.
CALL apoc.periodic.iterate(
"MATCH (u:User) WHERE u.processed = false RETURN u",
"SET u.processed = true",
{batchSize: 10000, parallel: false}
);Frequently Asked Questions (Neo4j Cypher Graph Queries & Index Tuning SOP)
Q:Can I use Neo4j Cypher Graph Queries & Index Tuning across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. It mounts identically in `.claude/skills/`, `.cursor/skills/`, and standard workspace agent folders across all four runtimes without modifications.
Q:How does Neo4j Cypher Graph Queries & Index Tuning prevent context window overflow during long agent sessions?
It restricts instructions to a declarative, 4-rule SOP in frontmatter. Instead of appending multi-page Neo4j manual documentation into the context window, it provides precise algorithmic heuristics for parameterized indexing and APOC procedure selection.
Q:Does this skill require escalated root or container permissions?
No. The skill has a security score of 98/100 with shell execution and network access disabled by default (`shell_exec: false`, `net_access: false`). It operates safely by producing clean, linted Cypher artifacts inside your local workspace.
Ready to equip your autonomous agent with Neo4j Cypher Graph Queries & Index Tuning?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.