本文へ移動
cccskills
無料GitHub で公開

neo4j-cypher-guide

Comprehensive 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, and Quantified Path Patterns (QPP) for efficient graph traversal.

インストール方法を見る

含まれるファイル(4)

  • SKILL.md7.1 KB
  • references/deprecated-syntax.md2.7 KB
  • references/qpp.md6.5 KB
  • references/subqueries.md4.4 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Neo4j Modern Cypher Query Guide

This skill helps generate Neo4j Cypher queries using modern syntax patterns and avoiding deprecated features. It focuses on efficient query patterns for graph traversal, data retrieval, and set-based writes.

Quick Compatibility Check

When generating Cypher queries, immediately avoid these REMOVED features:

  • ❌ id() function → Use 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

Core Principles for Query Generation

  1. Use modern syntax patterns - QPP for complex traversals, CALL subqueries for complex reads

  2. Optimize during traversal - Filter early within patterns, not after expansion

  3. Always filter nulls when sorting - Add IS NOT NULL checks for sorted properties

  4. Explicit is better than implicit - Always use explicit grouping and type checking

  5. Write set-based, not per-node - One query with a WHERE/property condition beats fetching nodes and mutating them one by one (an N+1). E.g. delete all rows for one owner in one shot:

    MATCH (n:Preference { owner_id: $owner_id })
    DETACH DELETE n
    

    not "fetch matching nodes, then run one DELETE per node".

Critical Sorting Rule

ALWAYS filter NULL values when sorting:

// 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

Query Pattern Selection Guide

For Simple Queries

Use standard Cypher patterns with modern syntax:

MATCH (n:Label {property: value})
WHERE n.otherProperty IS :: STRING
RETURN n

For Variable-Length Paths

Consider Quantified Path Patterns (QPP) for better performance:

// 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:

MATCH (p:Person)
WHERE count{(p)-[:KNOWS]->()} > 5
RETURN p.name,
       exists{(p)-[:MANAGES]->()} AS isManager

For Complex Read Operations

Use CALL subqueries for sophisticated data retrieval:

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

Common Query Transformations

Counting Patterns

// Old: RETURN size((n)-[]->())
// Modern: RETURN count{(n)-[]->()}

Checking Existence

// Old: WHERE exists((n)-[:REL]->())
// Modern: WHERE EXISTS {MATCH (n)-[:REL]->()}
// Also valid: WHERE exists{(n)-[:REL]->()}

Element IDs

// Old: WHERE id(n) = 123
// Modern: WHERE elementId(n) = "4:abc123:456"
// Note: elementId returns a string, not integer

Sorting with Null Handling

// 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 LAST

When to Load Reference Documentation

Load the appropriate reference file when:

references/deprecated-syntax.md

  • Migrating queries from older Neo4j versions
  • Encountering syntax errors with legacy queries
  • Need complete list of removed/deprecated features

references/subqueries.md

  • Working with CALL subqueries for reads
  • Using COLLECT or COUNT subqueries
  • Handling complex aggregations
  • Implementing sorting with null filtering

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

Query Generation Checklist

Before finalizing any generated query:

  1. ✅ No deprecated functions (id, btree indexes, etc.)
  2. ✅ Explicit grouping for aggregations
  3. ✅ NULL filters for all sorted properties
  4. ✅ Appropriate subquery patterns for reads
  5. ✅ Consider QPP for paths with filtering needs
  6. ✅ Use COUNT{} instead of size() for pattern counting
  7. ✅ Variable scope clauses in CALL subqueries
  8. ✅ Unique variable names for relationships

Error Resolution Patterns

"Implicit grouping key" errors

// 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"

// Use elementId() but note it returns a string, not integer

"Repeated variable" errors

// Problem: MATCH (a)-[r*]->(), (b)-[r*]->()
// Solution: MATCH (a)-[r1*]->(), (b)-[r2*]->()

Performance Tips

  1. Start with indexed properties - Always anchor patterns with indexed lookups
  2. Filter early in QPP - Apply WHERE clauses within the pattern
  3. Filter nulls before sorting - Prevent unexpected results and improve performance
  4. Limit expansion depth - Use reasonable upper bounds in quantifiers
  5. Use EXISTS for existence checks - More efficient than counting
  6. Profile queries - Use PROFILE to identify bottlenecks

Modern Cypher Features

Label Expressions

WHERE n:Label1|Label2  // OR
WHERE n:Label1&Label2  // AND
WHERE n:!Archived      // NOT

Dynamic Labels and Types

Labels and relationship types accept parameters (Neo4j 5.26+):

MATCH (n:$($label))                    // dynamic node label
MATCH (a)-[r:$($rel_type)]->(b)        // dynamic relationship type

Choosing between a dynamic label and interpolating the label into the query text is a performance tradeoff, not a style rule: each interpolated variant is planned and cached separately, but the planner generally does better with a static label than a dynamic one. If the label is the primary filter of the MATCH, prefer a static/interpolated label; when other indexed predicates carry the filtering, a dynamic label is more likely to be acceptable. When in doubt, PROFILE both.

Type Predicates

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

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.

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Analyzes recent CI failures on pull requests to identify flaky tests, using retry outcomes (failed attempt → green re-run) and cross-PR recurrence as evidence, and maintains a local longitudinal ledger so flakiness can be tracked over time. TRIGGER when: the user wants to find flaky tests, correlate recent CI failures, check which tests fail across PRs or recover on retry, or refresh the flakiness trend report. DO NOT TRIGGER when: babysitting a single PR's CI until green → monitoring-pull-requests; diagnosing or fixing one specific failing test → the bug-analysis skills.

日本語の概要は準備中です。原文の説明を表示しています。

opsmill/infrahub5342026年10月11日 更新

Audits internal (dev/) and external (docs/) documentation completeness for a feature, subject, or set of existing docs, maps changes indicated by the user, across Infrahub's documentation layers, reports gaps, and optionally applies the fixes. TRIGGER when: the user wants to audit or check documentation coverage, find doc gaps after a feature branch, or verify docs are still current for a subject or specific files. DO NOT TRIGGER when: authoring new documentation from scratch → use the add-docs flow; only linting/formatting Markdown → run `uv run invoke docs.lint`.

日本語の概要は準備中です。原文の説明を表示しています。

opsmill/infrahub5342026年10月11日 更新

commit

無料

Stages and commits the current changes onto a safe working branch, enforcing branch discipline and optionally pushing upstream. TRIGGER when: the user wants to commit, save, or check in the current changes. DO NOT TRIGGER when: opening a pull request → pr.

日本語の概要は準備中です。原文の説明を表示しています。

opsmill/infrahub5342026年10月11日 更新

Use when you've fixed a bug, added a feature, or made any user-facing change in a project that uses Towncrier and need to record it for the changelog — before committing or opening a PR, or whenever asked to add a changelog entry, towncrier fragment, or news fragment.

日本語の概要は準備中です。原文の説明を表示しています。

opsmill/infrahub5342026年10月11日 更新

Turns a single feature idea, improvement, or bug into ONE well-structured GitHub issue. TRIGGER when: the user wants to file/open/create an issue, turn a feature idea or improvement into a ticket, or capture something missing or broken as a ticket. DO NOT TRIGGER when: breaking work into multiple issues or planning a body of work → a planning skill; writing a full Product Requirements Document → creating-prd; the idea is still fuzzy and unhardened → grilling-ideas first.

日本語の概要は準備中です。原文の説明を表示しています。

opsmill/infrahub5342026年10月11日 更新

Synthesises the current conversation context into a Product Requirements Document and publishes it to GitHub (as a comment on a referenced issue, or a new issue). Synthesises from context; does not interview. TRIGGER when: the conversation has produced enough understanding of a feature and the user wants it captured as a PRD. DO NOT TRIGGER when: a single small issue is enough → creating-issues; the idea has not been stress-tested yet → grilling-ideas first; bug reports.

日本語の概要は準備中です。原文の説明を表示しています。

opsmill/infrahub5342026年10月11日 更新

opsmill のスキルをすべて見る

このスキルの問題を報告する