GraphRAG Patterns for Hybrid Search and Text2Cypher

VerifiedSafe

Implement RAG workflows with Neo4j using hybrid search, Text2Cypher, and agentic routing.

Sby Skills Guide Bot
Data & AIAdvanced
7/22/2026
Claude Code
#graphrag#neo4j#rag#text2cypher#hybrid-search

Recommended for

Automated summary

Provides implementation patterns for GraphRAG on Neo4j, covering hybrid vector/keyword search, Text2Cypher generation, query routing, graph-enriched context, and RAGAS evaluation.

Strengths

  • Concrete code snippets for each pattern: hybrid retriever, few-shot Cypher, query router, and graph-enriched search.
  • Covers the full retrieval lifecycle, from initial routing through RAGAS-based evaluation.
  • Builds on the langchain-neo4j and RAGAS ecosystem, making it easy to integrate into an existing project.

Limitations

  • Assumes a pre-modeled Neo4j graph with Article/Chapter labels and embeddings already in place.
  • Some examples are truncated, notably the stepback prompt, and need to be completed or adapted.
  • Does not cover index creation, performance tuning, or detailed Cypher error handling beyond validate_cypher.
When to use it

Use when building or improving a RAG pipeline on Neo4j that requires hybrid search, generated Cypher queries, or graph-aware retrieval.

When not to use it

Avoid when you need a complete Neo4j data modeling and ingestion guide, or when working with a non-graph vector store.

Security analysis

Safe
Quality score88/100

The skill contains only documentation and code examples for GraphRAG patterns using Neo4j/LangChain. It does not instruct destructive operations, credential exfiltration, obfuscated payloads, or safety-disabling behavior. The declared tools are limited to file reading/editing and searching.

No concerns found

How this analysis is made

Examples

Hybrid retriever setup
Create a hybrid vector and full-text retriever over my Neo4j Article nodes using langchain-neo4j, combining the content and summary properties.
Text2Cypher with few-shot examples
Add a Text2Cypher chain with few-shot examples and Cypher validation so users can ask questions like 'which chapters have the most articles?'
Router and evaluation pipeline
Build an agentic router that sends queries to vector, Cypher, or hybrid retrieval, then evaluate the results with RAGAS.

name: graphrag-patterns description: GraphRAG implementation patterns for hybrid search, Text2Cypher, and agentic retrieval. Use when implementing RAG workflows with Neo4j. allowed-tools: Read, Grep, Glob, Edit, Write

GraphRAG Patterns

Hybrid Search (Vector + Keyword)

Combine vector similarity with full-text search for better recall:

from langchain_neo4j import Neo4jVector

def create_hybrid_retriever(driver, embeddings):
    return Neo4jVector.from_existing_graph(
        embeddings,
        driver=driver,
        index_name="article_embeddings",
        keyword_index_name="article_fulltext",
        search_type="hybrid",  # Combines vector + keyword
        node_label="Article",
        text_node_properties=["content", "summary"],
        embedding_node_property="embedding",
    )

Text2Cypher with Few-Shot Examples

Always provide examples for better query generation:

FEW_SHOT_EXAMPLES = [
    {
        "question": "What articles discuss requirements traceability?",
        "cypher": '''
            MATCH (a:Article)
            WHERE a.content CONTAINS 'traceability'
            RETURN a.title, a.summary
            LIMIT 10
        '''
    },
    {
        "question": "Which chapters have the most articles?",
        "cypher": '''
            MATCH (c:Chapter)-[:CONTAINS]->(a:Article)
            RETURN c.title, count(a) as article_count
            ORDER BY article_count DESC
        '''
    },
]

from langchain_neo4j import GraphCypherQAChain

chain = GraphCypherQAChain.from_llm(
    llm=llm,
    graph=graph,
    cypher_prompt=CYPHER_PROMPT,
    example_selector=SemanticSimilarityExampleSelector.from_examples(
        FEW_SHOT_EXAMPLES,
        embeddings,
        k=3,
    ),
    validate_cypher=True,
)

Agentic Router Pattern

Route queries to the best retrieval strategy:

from langchain_core.prompts import ChatPromptTemplate

ROUTER_PROMPT = ChatPromptTemplate.from_template('''
Classify the query into one of these retrieval strategies:

- VECTOR: Semantic similarity search (concepts, topics, "similar to")
- CYPHER: Structured queries (counts, relationships, specific filters)
- HYBRID: Complex queries needing both approaches

Query: {query}

Strategy:''')

async def route_query(query: str, llm) -> str:
    response = await llm.ainvoke(ROUTER_PROMPT.format(query=query))
    return response.content.strip().upper()

Graph-Enriched Retrieval

Augment vector results with graph context:

async def graph_enriched_search(driver, query: str, embeddings) -> list[dict]:
    # Step 1: Vector search for relevant articles
    vector_results = await vector_search(driver, query, embeddings, limit=5)

    # Step 2: Expand with graph traversal
    article_ids = [r["id"] for r in vector_results]

    enrichment_query = '''
        MATCH (a:Article) WHERE a.id IN $ids
        OPTIONAL MATCH (a)<-[:CONTAINS]-(c:Chapter)
        OPTIONAL MATCH (a)-[:RELATED_TO]->(related:Article)
        RETURN a, c.title as chapter, collect(DISTINCT related.title) as related_articles
    '''

    enriched = await execute_read_query(driver, enrichment_query, {"ids": article_ids})
    return enriched

RAGAS Evaluation Metrics

Evaluate retrieval quality:

from ragas.metrics import (
    context_precision,
    context_recall,
    faithfulness,
    answer_relevancy,
)
from ragas import evaluate

def evaluate_retrieval(questions, ground_truths, contexts, answers):
    dataset = Dataset.from_dict({
        "question": questions,
        "ground_truth": ground_truths,
        "contexts": contexts,
        "answer": answers,
    })

    results = evaluate(
        dataset,
        metrics=[
            context_precision,
            context_recall,
            faithfulness,
            answer_relevancy,
        ],
    )
    return results

Stepback Prompting

For complex queries, generate a broader question first:

STEPBACK_PROMPT = '''
Given a specific question, generate a more general "stepback" question
that would help gather broader context before answering the specific question.

Specific question: {question}
Stepback question:'''

async def stepback_retrieval(query: str, retriever, llm):
    # Generate stepback question
    stepback_q = await llm.ainvoke(STEPBACK_PROMPT.format(question=query))

    # Retrieve for both questions
    specific_docs = await retriever.ainvoke(query)
    stepback_docs = await retriever.ainvoke(stepback_q.content)

    # Combine and deduplicate
    all_docs = {doc.page_content: doc for doc in specific_docs + stepback_docs}
    return list(all_docs.values())

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/download' --output '.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/SKILL.md.part' && mv '.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/SKILL.md.part' '.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Tools declared by the author (check availability in your agent): Read, Grep, Glob, Edit, Write

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/SKILL.md' && test -s '.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/graphrag-patterns' && cp -R '.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh' '.claude/skills/graphrag-patterns'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh'

openskills read 'graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/graphrag-patterns-for-hybrid-search-and-text2cypher-mrwakboh/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills