TL;DR: A single-vector RAG retrieval is limited to semantic similarity. By combining keyword matching, vector search, and graph traversal in Neo4j, you get three complementary signals that produce significantly more accurate LLM answers — all from one database.
Standard Retrieval-Augmented Generation (RAG) pipelines rely on a single mechanism: convert documents into embeddings, store them in a vector index, and retrieve the most similar chunks at query time. This works well for semantic matching but fails when queries require exact keyword hits or relational reasoning across entities.
This post walks through building a RAG pipeline using Neo4j that performs three-way retrieval — keyword search, vector similarity search, and graph traversal — then merges all context before passing it to an LLM for generation. The result is more accurate answers from the same underlying data.
Why Three-Way Retrieval?
A single-vector approach has blind spots:
- Keyword search: Exact term matching catches entities and proper nouns that embeddings dilute (“Elizabeth I” vs “elizabethan era”).
- Vector similarity: Semantic understanding finds conceptually related content even without shared vocabulary.
- Graph traversal: Relationship reasoning surfaces connections between entities — who succeeded whom, what countries are linked by treaties — impossible with flat vector stores.
Combining all three from one database eliminates the ETL overhead of maintaining separate keyword indexes, vector stores, and graph databases.
Setting Up Neo4j AuraDB
Neo4j offers a free cloud tier through AuraDB that requires no local installation. One free instance is included per account.
- Navigate to Neo4j Aura and click “Start Free.”
- Create a new instance — select the Free tier.
- Download the connection details (URI, username, password) from the dashboard. You’ll need these three values for your LangChain configuration.
The free AuraDB instance supports all retrieval features we need: full-text indexes, vector indexes, and native Cypher query execution.
Installing Dependencies
We use Google Colab with a free GPU runtime for this walkthrough, but any Python environment works. The core packages are:
pip install -q --upgrade langchain-core langchain-community langchain-openai langchain-experimental wikipedia neo4jUnderstanding the LangChain package split is important:
- langchain-core: Latest abstractions and LCEL (LangChain Expression Language).
- langchain-community: Third-party integrations — Neo4j, Wikipedia loaders, etc.
- langchain-openai: OpenAI-specific models and embeddings.
- langchain-experimental: Experimental chains and agents.
Loading Data with WikipediaLoader
For this example we use the Wikipedia article on Elizabeth I as our knowledge base. LangChain’s WikipediaLoader fetches and splits the content automatically:
from langchain_community.document_loaders import WikipediaLoader
loader = WikipediaLoader(query="Elizabeth I", load_max_docs=1, load_all_available_meta=True)documents = loader.load()The loader returns a list of Document objects with page text and metadata. Each document’s content is already structured — headings, paragraphs, and infobox data are preserved as plain text.
Creating the Neo4j Graph
We connect to AuraDB using LangChain’s Neo4jGraph:
from langchain_community.graphs import Neo4jGraph
graph = Neo4jGraph( url="neo4j+s://your-instance-url.databases.neo4j.io", username="neo4j", password="your-password")Once connected, we ingest the documents into the graph. LangChain’s Neo4jGraph can auto-extract entities and relationships from text using an LLM:
graph.add_documents(documents)This step calls OpenAI to identify entities (people, places, organizations) and their relationships from each document chunk, then writes them as nodes and edges in Neo4j. The result is a structured knowledge graph derived automatically from unstructured text.
Three-Way Retrieval Implementation
1. Keyword Search via Full-Text Index
Neo4j supports full-text indexes on node properties. We create one on the Document labels:
graph.query(""" CREATE FULLTEXT INDEX documentSearch IF NOT EXISTS FOR (n:Document) ON EACH [n.text]""")Then query it with Cypher to find exact keyword matches:
keyword_results = graph.query(f""" CALL db.index.fulltext.queryNodes('documentSearch', '{user_query}') YIELD node, score WHERE score > 0.5 RETURN node.text AS text, score""")2. Vector Similarity Search
Neo4j supports vector indexes natively. We embed each document chunk using OpenAI’s embedding model and store the vectors alongside the nodes:
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
# Create a vector index on Document nodesgraph.query(""" CREATE VECTOR INDEX documentVector IF NOT EXISTS FOR (n:Document) ON n.embedding OPTIONS {indexConfig: { `vector.dimensions`: 1536, `vector.similarity.function`: "cosine" }}""")Then perform similarity search:
query_embedding = embeddings.embed_query(user_query)
similarity_results = graph.query(f""" CALL db.index.vector.queryNodes('documentVector', 5, $embedding) YIELD node, score RETURN node.text AS text, score""", params={"embedding": query_embedding})3. Graph Traversal via Cypher
The power of Neo4j is relationship reasoning. We can traverse the graph to find connected entities:
graph_results = graph.query(""" MATCH (a {name: $entity})-[*1..2]->(b) RETURN a.name AS source, b.name AS target, collect(DISTINCT type(a--b)) AS relationships""", params={"entity": "Elizabeth I"})This finds all entities directly or indirectly connected to Elizabeth I through one or two hops — successors, advisors, countries ruled, conflicts fought.
Merging Context and Generating
The final step combines results from all three retrieval methods into a single context document:
from langchain_openai import ChatOpenAIfrom langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_template("""Answer the question based on the following context from multiple sources.
Keyword matches: {keyword_context}Vector similarities: {vector_context}Graph relationships: {graph_context}
Question: {query}""")
chain = prompt | llmresponse = chain.invoke({ "keyword_context": "\n".join([r["text"] for r in keyword_results]), "vector_context": "\n".join([r["text"] for r in similarity_results]), "graph_context": "\n".join([f"{r['source']} -> {r['target']}" for r in graph_results]), "query": user_query,})The LLM receives three complementary signals and can reason across them — using keyword matches for exact entities, vector context for semantic understanding, and graph relationships for structural reasoning.
Why This Is More Accurate Than Single-Vector RAG
A traditional vector-only RAG system retrieves chunks based purely on embedding similarity. If you ask “Who succeeded Elizabeth I?”, the vector search might return generic content about Tudor England but miss the explicit succession relationship encoded in the graph. The keyword search catches “Elizabeth” and “succession” directly, while the graph traversal traverses [:SUCCEEDED_BY] relationships to find Mary Stuart — all from the same database call.
The three signals are not redundant; they catch different failure modes of each other. Keyword misses semantic nuance but nails exact terms. Vectors understand meaning but blur proper nouns. Graphs reason about structure but require pre-extracted entities. Together, they cover more ground than any single approach alone.
References
- Realtime Powerful RAG Pipeline using Neo4j — S Savita (YouTube) — https://www.youtube.com/watch?v=Ik8gNjJ-13I
- Neo4j AuraDB Free Tier — neo4j.com/cloud/aura/
- LangChain Neo4j Integration — LangChain Docs — https://python.langchain.com/docs/integrations/graphs/neo4j_graph
This article was written by Gemini (Gemini 1.5 Pro | Google), based on content from: https://www.youtube.com/watch?v=Ik8gNjJ-13I



