Keyword Search and Hybrid Retrieval

Combine vector search and keyword matching in an existing RAG knowledge base, then merge and deduplicate the two result sets.

🎯 Introduction

We have learned to retrieve relevant material with Qdrant. For example, when a user asks, “Can I get a refund for sale items?”, the application converts the question into a vector and finds document chunks with similar meanings.

Vector search does not match text word by word. When a question includes a specific product name, error code, or clause, we can also search directly for material containing that text to complement vector retrieval.

For example, if the question contains “sale items,” we can check which passages actually contain that phrase alongside searching for semantically similar content.

We will apply this to our refund knowledge base: retrieve vector search results and keyword matches separately, then combine them into one deduplicated list.


🧱 Why Add Keyword Matching?

Consider these passages in the knowledge base:

MaterialContent
Refund policyYou can request a refund within 7 days of purchase. Sale items are nonrefundable.
Refund requirementsRefund requests require an order number and proof of purchase.
Shipping instructionsStandard orders ship within 48 hours of payment.

The user asks, “Can I get a refund for sale items?”

Vector search ranks passages by semantic similarity to the question. It might find the refund policy or other refund-related passages.

Keyword matching is more direct: check only whether a passage contains “Sale items.” Of the three passages above, only the first matches.

The two approaches therefore provide different signals: related meaning and the presence of specific text.


🛠 Step 1: Retrieve Vector Search Results

Continue using the existing rag_docs collection. Ensure Qdrant is running and that you have run 05.seed.mjs from the earlier lessons to store the refund, shipping, and support passages.

Create 09.hybrid-search.mjs and start with the familiar retrieval code:

import OpenAI from "openai";
import { QdrantClient } from "@qdrant/js-client-rest";

const ai = new OpenAI({
    apiKey: process.env.AI_API_KEY,
    baseURL: process.env.AI_BASE_URL
});
const qdrant = new QdrantClient({ url: "http://127.0.0.1:6333" });

const question = "Can I get a refund for sale items?";
const keyword = "Sale items";

const embedding = await ai.embeddings.create({
    model: process.env.AI_EMBEDDING_MODEL,
    input: question
});

const result = await qdrant.query("rag_docs", {
    query: embedding.data[0].embedding,
    limit: 2,
    with_payload: true
});

const semantic = result.points;
console.log("Vector search:");
for (const point of semantic) {
    console.log("-", point.payload.text);
}

This reuses vector search from earlier lessons. semantic contains the top two retrieved passages; their content and order depend on the actual query.

Save the file and run:

node --env-file=.env 09.hybrid-search.mjs

For example, you might see:

Vector search:
- Refund requests require an order number and proof of purchase.
- Refunds
  You can request a refund within 7 days of purchase. Sale items are nonrefundable.

This is illustrative output, not measured rankings. Your results may differ; first inspect which two passages are actually returned.

We retrieve two passages here to make it easy to observe whether keyword matching adds material later. Real projects do not need to use this fixed count.


🔎 Step 2: Find Passages Containing the Keyword

Now use a different approach: instead of calculating similarity, check whether the text contains “Sale items.”

Because this exercise knowledge base is small, we can read its records from Qdrant and match text in JavaScript.

Append this to 09.hybrid-search.mjs:

const page = await qdrant.scroll("rag_docs", {
    limit: 20,
    with_payload: true,
    with_vector: false
});

const matched = page.points.filter((point) =>
    typeof point.payload?.text === "string" &&
    point.payload.text.includes(keyword)
);

console.log("Keyword matches:");
for (const point of matched) {
    console.log("-", point.payload.text);
}

scroll() reads the test material, and includes(keyword) checks whether the text contains “Sale items.”

Save the added code and run the same file again:

node --env-file=.env 09.hybrid-search.mjs

This run prints vector results first, then keyword results. With the test data imported earlier, the keyword matching section displays:

Keyword matches:
- Refunds
  You can request a refund within 7 days of purchase. Sale items are nonrefundable.

Compare the two result sets. If vector search also found this refund policy, the results overlap. If it did not, keyword matching adds a new passage. Next, we will combine both lists.

This is string matching over a small dataset, not Qdrant full-text search. Large knowledge bases cannot be handled by reading all records at once like this; real applications need approaches such as full-text indexes or sparse retrieval. For now, focus on how results are combined.


🔗 Step 3: Merge and Deduplicate Results

We will use a simple rule: put keyword matches first, then add vector search results, keeping each passage only once.

How can we identify duplicates? Both approaches return Qdrant points, and a point’s id stays the same regardless of how it was found.

Append:

const merged = new Map();

for (const point of [...matched, ...semantic]) {
    if (!merged.has(point.id)) {
        merged.set(point.id, point);
    }
}

console.log("Merged results:");
for (const point of merged.values()) {
    console.log("-", point.payload.text);
}

The Map deduplicates by point ID: keyword matches go in first, then vector results add passages that are not already present.

Save the code from step 3 and run again:

node --env-file=.env 09.hybrid-search.mjs

If the first two steps produced the illustrative results above, the merged list is:

Merged results:
- Refunds
  You can request a refund within 7 days of purchase. Sale items are nonrefundable.
- Refund requests require an order number and proof of purchase.

The program prints all three result sets in sequence. Check your own output to confirm that each point appears only once in the merged list. If both retrieval methods found the refund policy, it appears first.

Keyword priority is simply a convenient merge rule for this demonstration; it does not guarantee the best ranking. More complex questions require considering relevance when deciding which material comes first. The next article, “RRF Rank Fusion,” addresses this.


❓ Knowledge Check

Q: If keyword matching finds “Sale items” directly, why not use it alone?

A user might ask, “Can I return discounted products?” while the source says “Sale items.” The meaning is similar, but the wording differs. Vector search may retrieve the passage, while matching only “discounted products” will not. The two approaches can therefore complement each other.


🧪 Exercise

Change question to “What documents do I need to request a refund?” and keyword to “proof of purchase.” Rerun the program. Check whether keyword matching finds the refund requirements and whether the merged list contains duplicates.

Success criteria: Explain what vector search and keyword matching each use to find material, why merging requires deduplication by point ID, and why keyword priority does not imply an optimal ranking.


🎉 Congratulations! You can now combine vector search with keyword matching over an existing knowledge base and merge both result sets without duplicates.