A support question can hold two questions at once, as 'why was my card declined and when do I get my money back' does. Its words match the article about declines, while the article about refunds has one content word in common with it, which is card. In hybrid mode, the engine performs a keyword search and a similarity search over one index in a single query and merges the two rankings, so the customer can find an answer to either half.
Every example on this page is part of one program for a help desk of five articles. The program first sends one question in hybrid mode, alongside the two separate searches that the engine fuses. In later steps, the program moves the weight onto the similarity side and pages through the fused list in a fixed order. Each code block below holds the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.
Install a model that works inside your process
The engine embeds every article and every question through an embedding adapter, which calls all-MiniLM-L6-v2 inside your process with no API key. In TypeScript, @delali/narsil-embeddings-transformers provides that adapter. In Python, Go, and Rust, the adapter is a short class or type that you write around fastembed or hugot, following the steps on Embedding adapters. Each library downloads the model the first time that your program loads it.
pnpm add @delali/narsil @delali/narsil-embeddings-transformers @huggingface/transformersAnswer a question that holds two questions
The engine holds the adapter under the name minilm, while embedding.fields lists, for the vector field, the text fields that the engine embeds into it. Each insert therefore holds only a title and a body, which the engine embeds into embedding. On the vector search page, the program embeds the text itself and passes each vector in, which is the other way to fill that field.
A hybrid query holds both inputs. term is the text that the engine scores with BM25 in the keyword search, while vector holds the text or the vector that the engine compares in the similarity search. The engine then merges the two rankings. The program also sends the same question to each search separately, so that you can see the two lists that the engine merges.
import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
const narsil = await createNarsil({
embeddingAdapters: { minilm: createTransformersEmbedding({ dimensions: 384 }) },
})
await narsil.createIndex('help-desk', {
schema: { title: 'string', body: 'string', embedding: 'vector[384]' },
embedding: { adapter: 'minilm', fields: { embedding: ['title', 'body'] } },
})
await narsil.insertBatch('help-desk', [
{
id: 'refund-timing',
title: 'How a refund reaches your bank',
body: 'A refund returns to the card that paid for the order, and your bank posts it within five working days.',
},
{
id: 'gateway-declines',
title: 'What the checkout does with a declined card',
body: 'The gateway answers with code NRS-429 when a shopper sends more card attempts than it allows in a minute.',
},
{
id: 'payout-schedule',
title: 'When a payout reaches your account',
body: 'Payouts leave on working days, and the bank credits them on the next working day.',
},
{
id: 'parcel-tracking',
title: 'Track a parcel after dispatch',
body: 'Every dispatched order has a tracking code, and the carrier updates it at each depot.',
},
{
id: 'reader-replacement',
title: 'Replace a reader that stops charging',
body: 'Send back the unit marked R7-Mini on its base, and a replacement arrives within two working days.',
},
])
const question = 'why was my card declined and when do I get my money back'
const keyword = await narsil.query('help-desk', { term: question, limit: 4, document: false })
const similar = await narsil.query('help-desk', {
mode: 'vector',
vector: { field: 'embedding', text: question },
limit: 4,
document: false,
})
const fused = await narsil.query('help-desk', {
mode: 'hybrid',
term: question,
vector: { field: 'embedding', text: question },
limit: 4,
document: false,
})
console.log(
JSON.stringify(
{
keyword: keyword.hits.map((hit) => hit.id),
similar: similar.hits.map((hit) => hit.id),
fused: fused.hits.map((hit) => ({ id: hit.id, score: hit.score })),
},
(key, value) => (typeof value === 'number' ? Number(value.toFixed(4)) : value),
2
)
)
await narsil.shutdown(){
"keyword": [
"gateway-declines",
"reader-replacement",
"refund-timing"
],
"similar": [
"gateway-declines",
"refund-timing",
"reader-replacement",
"payout-schedule"
],
"fused": [
{
"id": "gateway-declines",
"score": 0.0328
},
{
"id": "reader-replacement",
"score": 0.032
},
{
"id": "refund-timing",
"score": 0.032
},
{
"id": "payout-schedule",
"score": 0.0156
}
]
}The keyword list holds three documents, because three of the five hold a word from the question. The similarity list holds four, which is its limit, because the engine scores every stored vector against the question.
Under reciprocal rank fusion, the default strategy, the engine scores a document as 1 / (k + rank) on each list where it appears, with ranks counting from 1 and k at 60 unless the query sets another. The decline article is first on both lists, so its score is 1/61 + 1/61, or 0.0328. The reader article is second on keywords and third on meaning, while the refunds article is third on keywords and second on meaning, so both of them score 1/62 + 1/63, or 0.032. The engine breaks that tie on the document id. The payout article appears on only one list, so its score is a single 1/64, which puts it last at 0.0156.
Under that arithmetic, a document near the top of both lists scores higher than a document near the top of one list, so the decline article comes clearly first. However, the engine uses only the ranks under this strategy, so it gives the same score to two documents that swap places between the lists, as it does to the reader article and the refunds article here. A larger k flattens the difference between the ranks. At a k of 600, each of the top three documents of this query has a score of 0.0033, while at a k of 1, their scores spread from 1 to 0.5833. Set k to a whole number of 1 or more; the engine raises CONFIG_INVALID for any other value. The engine raises SEARCH_INVALID_MODE for a hybrid query that also sets a sort, because it orders hybrid hits by the fused score.
Weight the similarity side
Under the linear strategy, the engine blends the scores in place of the ranks. The engine normalises each list against the lowest and the highest score in that list, so the top of each list is 1 and the bottom is 0. It then scores every document as alpha * similarity + (1 - alpha) * keyword, counting a document missing from a list as 0 there. alpha is the weight of the similarity side, which is 0.5 unless you set another. The engine raises CONFIG_INVALID for an alpha outside the range 0 to 1.
import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
const narsil = await createNarsil({
embeddingAdapters: { minilm: createTransformersEmbedding({ dimensions: 384 }) },
})
await narsil.createIndex('help-desk', {
schema: { title: 'string', body: 'string', embedding: 'vector[384]' },
embedding: { adapter: 'minilm', fields: { embedding: ['title', 'body'] } },
})
await narsil.insertBatch('help-desk', [
{
id: 'refund-timing',
title: 'How a refund reaches your bank',
body: 'A refund returns to the card that paid for the order, and your bank posts it within five working days.',
},
{
id: 'gateway-declines',
title: 'What the checkout does with a declined card',
body: 'The gateway answers with code NRS-429 when a shopper sends more card attempts than it allows in a minute.',
},
{
id: 'payout-schedule',
title: 'When a payout reaches your account',
body: 'Payouts leave on working days, and the bank credits them on the next working day.',
},
{
id: 'parcel-tracking',
title: 'Track a parcel after dispatch',
body: 'Every dispatched order has a tracking code, and the carrier updates it at each depot.',
},
{
id: 'reader-replacement',
title: 'Replace a reader that stops charging',
body: 'Send back the unit marked R7-Mini on its base, and a replacement arrives within two working days.',
},
])
const question = 'why was my card declined and when do I get my money back'
const keyword = await narsil.query('help-desk', { term: question, limit: 4, document: false })
const similar = await narsil.query('help-desk', {
mode: 'vector',
vector: { field: 'embedding', text: question },
limit: 4,
document: false,
})
const fused = await narsil.query('help-desk', {
mode: 'hybrid',
term: question,
vector: { field: 'embedding', text: question },
hybrid: { strategy: 'linear', alpha: 0.7 },
limit: 4,
document: false,
})
console.log(
JSON.stringify(
{
keyword: keyword.hits.map((hit) => hit.id),
similar: similar.hits.map((hit) => hit.id),
fused: fused.hits.map((hit) => ({ id: hit.id, score: hit.score })),
},
(key, value) => (typeof value === 'number' ? Number(value.toFixed(4)) : value),
2
)
)
await narsil.shutdown(){
"keyword": [
"gateway-declines",
"reader-replacement",
"refund-timing"
],
"similar": [
"gateway-declines",
"refund-timing",
"reader-replacement",
"payout-schedule"
],
"fused": [
{
"id": "gateway-declines",
"score": 1
},
{
"id": "refund-timing",
"score": 0.603
},
{
"id": "reader-replacement",
"score": 0.4056
},
{
"id": "payout-schedule",
"score": 0.3255
}
]
}Under the blend, the engine gives different scores to the two articles that tied under rank fusion. The decline article is first on both normalised lists, so its score is 1 whatever alpha you choose. The refunds article has a score of 0.603 and the reader article has a score of 0.4056, while under rank fusion, both of them score 0.032. A rank holds only the order of two documents, so the engine discards the distance between their scores under rank fusion, while it keeps that distance under the blend. Start on rank fusion, and move to the blend once you measure the keyword and similarity scores of the documents in your corpus.
Keep the same order on every page
When you leave depth out of a hybrid query, the engine fetches only enough vector results to reach the end of the requested page. For each later page, the engine therefore fuses a deeper vector list, so the fused order can change from one page to the next. With depth, you fix the length of both lists. With depth set, the engine fetches that many results from each of the two searches and fuses them once. The engine then takes every page of the query from the top depth of that fused list, whether you page with offset or with the cursor that each result holds.
The last page ends at depth, so it can hold fewer hits than limit. The engine raises SEARCH_RESULT_WINDOW_EXCEEDED for a page that starts at depth or beyond. Set depth to a whole number from 1 to 10,000. With a larger value, a reader can page further, although the engine then fetches more results from each search for every page.
import { createNarsil } from '@delali/narsil'
import { createNarsil, NarsilError } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
const narsil = await createNarsil({
embeddingAdapters: { minilm: createTransformersEmbedding({ dimensions: 384 }) },
})
await narsil.createIndex('help-desk', {
schema: { title: 'string', body: 'string', embedding: 'vector[384]' },
embedding: { adapter: 'minilm', fields: { embedding: ['title', 'body'] } },
})
await narsil.insertBatch('help-desk', [
{
id: 'refund-timing',
title: 'How a refund reaches your bank',
body: 'A refund returns to the card that paid for the order, and your bank posts it within five working days.',
},
{
id: 'gateway-declines',
title: 'What the checkout does with a declined card',
body: 'The gateway answers with code NRS-429 when a shopper sends more card attempts than it allows in a minute.',
},
{
id: 'payout-schedule',
title: 'When a payout reaches your account',
body: 'Payouts leave on working days, and the bank credits them on the next working day.',
},
{
id: 'parcel-tracking',
title: 'Track a parcel after dispatch',
body: 'Every dispatched order has a tracking code, and the carrier updates it at each depot.',
},
{
id: 'reader-replacement',
title: 'Replace a reader that stops charging',
body: 'Send back the unit marked R7-Mini on its base, and a replacement arrives within two working days.',
},
])
const question = 'why was my card declined and when do I get my money back'
const keyword = await narsil.query('help-desk', { term: question, limit: 4, document: false })
const similar = await narsil.query('help-desk', {
mode: 'vector',
vector: { field: 'embedding', text: question },
limit: 4,
document: false,
})
const fused = await narsil.query('help-desk', {
mode: 'hybrid',
term: question,
vector: { field: 'embedding', text: question },
hybrid: { strategy: 'linear', alpha: 0.7 },
limit: 4,
document: false,
})
const page = (offset: number) =>
narsil.query('help-desk', {
mode: 'hybrid',
term: question,
vector: { field: 'embedding', text: question },
hybrid: { strategy: 'linear', alpha: 0.7, depth: 4 },
limit: 2,
offset,
document: false,
})
const first = await page(0)
const second = await page(2)
let pastDepth: string | null = null
try {
await page(4)
} catch (error) {
pastDepth = error instanceof NarsilError ? error.code : String(error)
}
console.log(
JSON.stringify(
{
keyword: keyword.hits.map((hit) => hit.id),
similar: similar.hits.map((hit) => hit.id),
fused: fused.hits.map((hit) => ({ id: hit.id, score: hit.score })),
count: first.count,
first: first.hits.map((hit) => hit.id),
second: second.hits.map((hit) => hit.id),
pastDepth,
},
(key, value) => (typeof value === 'number' ? Number(value.toFixed(4)) : value),
null,
2
)
)
await narsil.shutdown(){
"count": 4,
"first": [
"gateway-declines",
"refund-timing"
],
"second": [
"reader-replacement",
"payout-schedule"
],
"pastDepth": "SEARCH_RESULT_WINDOW_EXCEEDED"
}The first two pages hold the four documents of the fused list in the blended order, while the engine refuses the third page because it starts at the depth. With depth set on a single engine, count is the number of documents that match a keyword plus the number of vector results that match no keyword, which is the three keyword matches and the payout article here. When you leave depth out, count is the length of the fused list. countExact is true only when each of the two rankings holds every matching document, so on a field that holds a graph, the engine reports a count at or below the true total.
Where to go next
- Read Vector search for the vector field itself, the promotion threshold, and the graph that the engine searches for the similarity half of this query.
- Read Full-text search for the BM25 scoring, the fuzzy matching, and the field boosts in the keyword half.
- Read Embedding adapters for the adapter with which the engine embeds this index, and for the steps to write one in each language.
- Read Reranking for a second model whose scores the engine uses to reorder the top of a fused list.