### Privileged issue
- [x] I am a LangChain maintainer, or was asked directly b…y a LangChain maintainer to create an issue here.
### Issue Content
This was first proposed on the forum, where I was advised to open an issue here:
https://forum.langchain.com/t/js-langchain-qdrant-add-a-hybrid-retrieval-mode-parity-with-langchain-qdrant-for-python/5041
I searched the issues and PRs for hybrid, sparse and BM25 support in `@langchain/qdrant` and found
none. I'd like to implement this myself: if the design below works for you, please assign the issue
to me.
## Summary
Since July 2024 the Python `QdrantVectorStore` has a `retrieval_mode` option, with dense, sparse and
hybrid modes ([langchain-ai/langchain#24164](https://github.com/langchain-ai/langchain/pull/24164)).
`@langchain/qdrant` (1.0.3) still writes and queries a single unnamed dense vector. This issue
proposes a hybrid mode for the JS package.
## Use case
Hybrid search helps when queries hinge on exact terms that dense retrieval alone handles poorly:
identifiers, section numbers, acronyms, product codes, proper names. Python users of the package
already have it.
In JS today you can already create a collection with a sparse vector, through `collectionConfig`, but
nothing in the store writes or queries it. The only way to get hybrid search is to bypass the vector
store: call `QdrantClient` directly for both indexing and search, and wrap it in a custom
`BaseRetriever`. That works, but it duplicates the vector store, and `asRetriever()` and existing
chains don't benefit.
## Why this is easier now than it used to be
The Python hybrid mode computes sparse vectors on the client with FastEmbed (`FastEmbedSparse`),
which has no JS equivalent. Since 1.15.3, a self-hosted Qdrant can do it on the server instead:
- the point carries a `Document` (`{ text, model: "qdrant/bm25", options: { language } }`), and
Qdrant turns it into a sparse BM25 vector, with language-specific stemming and stop words;
- `modifier: "idf"` on the sparse vector makes Qdrant compute IDF over the whole collection.
So the feature needs no new dependency. A prototype works on Qdrant 1.15.3 and 1.19.1 with
`@qdrant/js-client-rest` 1.20, the version on `main`. The `language` option does matter. With
`language: "italian"`, a query with "contratti" matches a chunk that only contains "contratto". With
the default (English), it finds nothing.
## Proposed API
```ts
const store = await QdrantVectorStore.fromExistingCollection(embeddings, {
url,
collectionName: "docs",
retrievalMode: "hybrid", // "dense" (default) | "hybrid"
sparseVectorName: "langchain-sparse", // default, same as Python
sparseDocumentOptions: { // passed as-is to the Qdrant Document
model: "qdrant/bm25",
options: { language: "english" },
},
});
await store.similaritySearch("how long can a fixed-term contract last?", 5); // hybrid
store.asRetriever({ k: 5 }); // hybrid as well
```
| Option | Default | Notes |
|---|---|---|
| `retrievalMode` | `"dense"` | the default keeps today's behaviour |
| `vectorName` | `""` (unnamed) | same as Python; today's collections keep working |
| `sparseVectorName` | `"langchain-sparse"` | same as Python |
| `sparseDocumentOptions` | `{ model: "qdrant/bm25" }` | model and BM25 options (`language`, `k`, `b`, `avg_len`, …) |
| `hybridFusion` | `{ fusion: "rrf" }` | same default as Python; any Qdrant fusion query (`dbsf`, or weighted `rrf` on Qdrant ≥ 1.17) |
## Behaviour
- **`ensureCollection`**, in `hybrid` mode and without a `collectionConfig`, creates the dense vector
plus a sparse vector with `modifier: "idf"`. A `collectionConfig` passed by the user is used as is,
as today.
- **`addVectors`** also writes the sparse vector, built from `document.pageContent`. Its signature
already receives the documents, so it does not change.
- **`similaritySearch` and `similaritySearchWithScore`** are overridden. In `hybrid` mode they send a
single `query` with two prefetches, one dense and one sparse, each with limit `k` and with the
filter applied to both, plus the fusion. This is the same shape as the Python implementation. In
`dense` mode the request is the same as today.
- **`similaritySearchVectorWithScore` and `maxMarginalRelevanceSearch` always search the dense vector**
(`using: vectorName`), as Python's by-vector search and MMR do. MMR keeps using Qdrant's built-in
MMR (#8574).
- **Existing collections.** A sparse vector cannot be added to an existing collection:
`PATCH /collections/{name}` answers `Not existing vector name error`. So `hybrid` mode needs a new
collection. The dense vector can stay unnamed next to a named sparse vector, though (tested on
1.15.3 and 1.19.1), so a collection created in `hybrid` mode can still be queried in `dense` mode.
## Impact on the `VectorStore` interface
None in `@langchain/core`: the change is limited to overrides in `@langchain/qdrant`. That is also
why it can't be done without overrides. The base `similaritySearch` and `similaritySearchWithScore`
embed the query and pass only the vector to `similaritySearchVectorWithScore`, so the query text
never reaches the sparse side.
Two semantic caveats, to be documented:
- **In hybrid mode, `similaritySearchWithScore` returns a fusion score, not a similarity.** Thresholds
become meaningless, for example in `ScoreThresholdRetriever`, which filters on
`score >= minSimilarityScore`.
- **`VectorStore` requires an `embeddings` instance.** A sparse-only mode, which Python supports with
`embedding=None`, would not fit as cleanly, so I'd leave it out of the first PR.
## Minimum Qdrant versions
I checked these against the release notes and ran them on the official Docker images:
| Feature | Minimum version | Notes |
|---|---|---|
| Query API (`prefetch` + `fusion`) | 1.10 | needed by the Python implementation too |
| Server-side BM25 on a self-hosted instance | **1.15.3** | Local BM25 first shipped in 1.15.2 ([qdrant/qdrant#6891](https://github.com/qdrant/qdrant/pull/6891)). There, however, the inference service starts only when a cloud inference address is configured, so a default instance answers `InferenceService is not initialized` (also on 1.15.1). 1.15.3 ([qdrant/qdrant#7056](https://github.com/qdrant/qdrant/pull/7056)) makes that configuration optional, enables stemming and stop words by default, and adds `language`. |
| Weighted RRF (`rrf: { weights }`) | 1.17.0 | [qdrant/qdrant#8063](https://github.com/qdrant/qdrant/pull/8063); 1.15.3 rejects it. Plain RRF is enough for the default. |
So `hybrid` mode would require Qdrant ≥ 1.15.3, while `dense` mode keeps working on any version.
## Open questions
1. **A mode on the store, or a separate method?** The mode follows Python; a separate method follows
the Weaviate JS store, which has `hybridSearch(query, options)` next to a dense
`similaritySearch`. I'd prefer the mode, because `asRetriever()` and existing chains get hybrid
search for free. Would you rather follow the Weaviate precedent?
2. **Sparse-only mode**: in the first PR or later?
3. **Precomputed sparse vectors**: is server-side BM25 enough, or should there also be a way to pass
sparse vectors computed elsewhere (like Python's `SparseEmbeddings`)?
4. **Validation**: should `hybrid` mode check up front that the server is ≥ 1.15.3 and that the
collection has the sparse vector, for example in `ensureCollection`, or rely on Qdrant's errors
and document the requirements?
## Test cases
Unit tests, with a mocked client:
- `dense` mode sends exactly today's requests;
- `hybrid` mode sends two prefetches with the right `using`, the filter on both, and the default and
custom fusion;
- `ensureCollection` creates the sparse vector with `modifier: "idf"`, and leaves a user
`collectionConfig` untouched;
- `addVectors` writes both vectors.
Integration tests, against a real Qdrant ≥ 1.15.3:
- in `hybrid` mode, a chunk that only BM25 can find (via stemming) is returned, and in `dense` mode
it is not;
- the filter is respected in `hybrid` mode;
- `asRetriever()` returns the hybrid results;
- an existing unnamed-vector collection still works in `dense` mode;
- `hybrid` mode on a collection without the sparse vector fails with a clear error.
## Scope
The PR would touch only `libs/providers/langchain-qdrant`, plus a changeset (`@langchain/qdrant`:
minor). The docs page lives in `langchain-ai/docs`
(`src/oss/javascript/integrations/vectorstores/qdrant.mdx`), so its update would be a separate PR
there.