Similarity Search and Result Filtering

Perform semantic search with Qdrant and compare how top-k, similarity scores, and source filters affect the results.

🎯 Introduction

In the previous article, we stored a chunk vector in Qdrant and read it back by ID. In a real RAG application, however, users ask questions without knowing the ID of the material they need.

This time, Qdrant will find relevant material using the question’s vector. We will add several test records, then observe how top-k, similarity scores, and source filters affect retrieval. This article focuses on retrieval without repeating the subsequent answer generation step.


🧱 Can the Closest Match Always Answer the Question?

Suppose the knowledge base only says, “Customer support is available daily from 9:00 to 18:00,” but the user asks, “What is the customer support phone number?”

Qdrant might rank the support hours highly because the topic is similar. But that passage contains no phone number. Ranking first means being relatively similar, not necessarily being able to answer the question.

We will control retrieval results in three ways:

MethodWhat it controls
Top-kThe maximum number of candidate passages returned
Similarity scoreHow close a candidate is to the question, allowing us to try excluding low-scoring results
Metadata filterThe search scope, such as a particular source file

🛠 Prepare Material for Comparison

The previous article wrote only one point. Setting limit: 3 would still return at most one result, which is not enough to compare rankings. We will prepare four passages first.

Continue using the rag_docs collection, Node.js 24.x, openai@7.62.0, and @qdrant/js-client-rest@1.20.0. Ensure Qdrant is running and that AI_API_KEY, AI_BASE_URL, and AI_EMBEDDING_MODEL in .env are valid. These dependencies and settings were prepared earlier, so you do not need to install them again.

Create 05.seed.mjs and prepare the material and clients:

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 collection = "rag_docs";

const documents = [
    {
        id: "fb1359e8-82d1-4c7a-9e67-eeabe6fc47bc",
        text: "Refunds\nYou can request a refund within 7 days of purchase. Sale items are nonrefundable.",
        source: "guide.md"
    },
    {
        id: "62f889f1-4251-4f38-945d-948d1799e499",
        text: "Refund requests require an order number and proof of purchase.",
        source: "guide.md"
    },
    {
        id: "3dc3e6da-a3e1-43ac-8a9f-656110ccf96f",
        text: "Standard orders ship within 48 hours of payment.",
        source: "shipping.md"
    },
    {
        id: "2be00876-0ba9-4f3a-9ca2-2c70fec4f15a",
        text: "Customer support is available daily from 9:00 to 18:00.",
        source: "support.md"
    }
];

The first passage reuses the previous point ID; the other three use different valid UUIDs. Rerunning the script updates these four records rather than continually inserting duplicates.

Append embedding generation and storage to the same file:

const points = [];

for (const doc of documents) {
    const result = await ai.embeddings.create({
        model: process.env.AI_EMBEDDING_MODEL,
        input: doc.text
    });

    points.push({
        id: doc.id,
        vector: result.data[0].embedding,
        payload: { text: doc.text, source: doc.source }
    });
}

await qdrant.upsert(collection, {
    wait: true,
    points
});

console.log(`Prepared ${points.length} test passages`);

This reuses embeddings and upsert() solely to prepare retrieval data. Their basic principles were covered earlier.

Run:

node --env-file=.env 05.seed.mjs

Expected output:

Prepared 4 test passages
Prepare the test data once. Repeated search runs do not need new document vectors; rerun 05.seed.mjs only when you change the test material. Any other points already in rag_docs remain and may affect results. For clarity, use the simple collection from the previous exercise and be aware of its existing data.

🔍 Retrieve Material Using a Question

Create 05.search.mjs, initialize the clients, and generate the question vector:

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 = "Within how many days must I request a refund?";

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

const queryVector = result.data[0].embedding;

queryVector is the vector for the user’s question. It must be generated using the same embedding model as the stored document vectors so they can be compared in a compatible vector space.

Append a Qdrant query:

const results = await qdrant.query("rag_docs", {
    query: queryVector,
    limit: 3,
    with_payload: true
});

for (const point of results.points) {
    console.log(
        point.score.toFixed(3),
        point.payload?.text,
        point.payload?.source
    );
}

query takes the question vector; limit: 3 returns at most three results; and with_payload: true includes the original text and source rather than just scores.

Run:

node --env-file=.env 05.search.mjs

You will see each candidate’s score, text, and source. The following illustrates the output format only; these scores and rankings are not measured results:

0.842 Refunds\nYou can request a refund within 7 days of purchase. Sale items are nonrefundable. guide.md
0.714 Refund requests require an order number and proof of purchase. guide.md
0.391 Standard orders ship within 48 hours of payment. shipping.md

With the Cosine configuration used in this course, a higher score generally indicates closer vectors. Regardless of the score, inspect payload.text to see whether it actually answers the question.


⚖️ Compare Top-k and Score Thresholds

Top-k: Control the Number of Results

Change limit: 3 to limit: 1 and rerun 05.search.mjs.

The query now returns at most one record. Change it back to 3 to allow more candidates. For policies with conditions and exceptions, too few candidates can omit important chunks, while too many can introduce irrelevant material. Top-k controls quantity, not correctness.

Score Threshold: Exclude Low-Scoring Candidates

Now change the query object to:

const results = await qdrant.query("rag_docs", {
    query: queryVector,
    limit: 3,
    score_threshold: 0.6,
    with_payload: true
});

The added score_threshold sets a similarity score cutoff. With the current Cosine configuration, results below this cutoff are excluded, so the final count may be less than limit or even zero.

0.6 is only an experimental value for observing the effect, not a universal standard for every model. Use the actual scores from the previous run to choose a value between candidate scores, then observe the change.

If you ask for a support phone number when the knowledge base only contains support hours, a threshold cannot establish that a passage contains the number. Score filtering can remove some irrelevant candidates, but it cannot replace checking the evidence for an answer.


🧩 Filter by Source

The preceding queries search the whole collection. Suppose only the shipping policies in shipping.md may be searched. Add a payload filter to restrict the query.

Remove the experimental score_threshold and change the query to:

const results = await qdrant.query("rag_docs", {
    query: queryVector,
    limit: 3,
    filter: {
        must: [
            { key: "source", match: { value: "shipping.md" } }
        ]
    },
    with_payload: true
});

This condition means:

  • must: Candidate records must satisfy the listed conditions.
  • key: "source": Check the point’s payload.source field.
  • match.value: Keep only records whose source is shipping.md.

Even a refund question will search only shipping.md. If the test collection contains only the four records above, the result will contain just the shipping passage; it will not automatically switch to refund documents because the result is irrelevant.

This illustrates that filters control search scope, while scores measure similarity within that scope. They address different concerns.

If you later provide knowledge bases to different users, source or permission filters must be set by the server based on user identity. Do not trust filter conditions supplied by the browser. The source filter here is only a basic demonstration.

❓ Knowledge Check

Q: How do score_threshold and filter differ?

score_threshold excludes low-scoring vector matches; filter restricts which records may participate in the query based on payload fields. For example, the former may remove weak matches, while the latter can limit retrieval to a particular source. They can be combined, but neither replaces the other.


🧪 Exercise

Continue using 05.search.mjs:

  1. Remove filter and score_threshold, then compare the result counts and content with limit: 1 and limit: 3.
  2. Set score_threshold, adjust it based on actual scores, and observe how the results change.
  3. Remove the threshold and add a filter for source: "guide.md". Verify that only material from that file is returned.

Success criteria: Explain that top-k controls count, score thresholds filter by match strength, and filters restrict source scope. Explain why ranking first does not mean a passage can answer the question.


🎉 Congratulations! You can now perform similarity search with Qdrant and inspect and filter candidate material using top-k, score thresholds, and metadata filters.