Search modes

Vector search

Embed text with a model inside your process, store the vectors in a typed field, and search by meaning in TypeScript, Python, Go, or Rust, with a similarity floor, a graph that the engine builds as the field grows, and compaction after a removal.

In a keyword search, the engine compares the words in a question with the words in each article. Suppose that a customer asks your help centre when their money comes back, while the article on that subject contains the word refund. A keyword search for that question can then return no article at all. In a vector search, the engine compares the numbers that an model produces for each text, so the engine can put that refunds article first.

This page contains two programs. The first program stores six help-centre articles and searches them by meaning. The second program grows an index to 5,000 articles so that you can watch the engine build a graph and then clear the tombstones once the program removes a fifth of the articles. Each code block below contains the whole file, where green lines show the lines that you add at each step and struck lines show the lines that you remove.

Install a model that works inside your process

Every program on this page embeds its text with all-MiniLM-L6-v2, a model that your program loads into its process without an API key. In TypeScript, the Transformers.js adapter from @delali/narsil-embeddings-transformers loads that model. The Python, Go, and Rust packages include no embedding model, so in those languages your code calls fastembed in Python and Rust, or hugot in Go, to embed the text. Each library downloads the model on its first call and loads it from a local folder after that.

pnpm add @delali/narsil @delali/narsil-embeddings-transformers @huggingface/transformers

Find an article with no word from the question

all-MiniLM-L6-v2 produces 384 numbers for each text, so the program declares the field as vector[384]. The engine raises VECTOR_DIMENSION_MISMATCH for a vector of any other length. The program embeds the title and the body of each article as one text so that a question can match either of them. The program stores each vector with its article. In TypeScript, the adapter embeds the articles under the 'document' purpose and the question under 'query', so that an adapter for an asymmetric model can add a separate prefix to each kind of text.

The program then sends one question to the index twice. The first query contains a term, which puts the engine in keyword mode, while the second contains mode: 'vector' and the vector of the question. With the document projection, the engine returns only title, so the program prints the title of each article without its 384 numbers. The engine in every language leaves the vector out of a hit even without the projection, because it returns a vector field only when the include list of the projection contains that field, when you set vectors: true in the projection, or when you create the index with returnVectors: true. Read Indexes and documents for each of those settings.

import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const articles = [
  {
    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: '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: 'password-reset',
    title: 'Reset the password on your account',
    body: 'A reset link arrives by email and stays valid for one hour.',
  },
  {
    id: 'mobile-card-payments',
    title: 'Take card payments in the mobile app',
    body: 'The mobile reader pairs over Bluetooth and settles to the same account as the web checkout.',
  },
  {
    id: 'api-key-rotation',
    title: 'Rotate an API key',
    body: 'A new key works at once, and the old key keeps answering for twenty-four hours.',
  },
  {
    id: 'billing-statement',
    title: 'Read your monthly billing statement',
    body: 'The statement lists every charge, every refund, and the fees deducted before payout.',
  },
]
 
const vectors = await embedding.embedBatch(
  articles.map((article) => `${article.title}. ${article.body}`),
  'document'
)
 
const narsil = await createNarsil()
 
await narsil.createIndex('articles', {
  schema: { title: 'string', body: 'string', embedding: 'vector[384]' },
})
 
await narsil.insertBatch(
  'articles',
  articles.map((article, position) => ({ ...article, embedding: vectors[position] }))
)
 
const question = 'when do I get my money back'
 
const keyword = await narsil.query('articles', {
  term: question,
  limit: 3,
  document: { include: ['title'] },
})
 
const similar = await narsil.query('articles', {
  mode: 'vector',
  vector: { field: 'embedding', value: await embedding.embed(question, 'query') },
  limit: 3,
  document: { include: ['title'] },
})
 
console.log(
  JSON.stringify(
    { question, keyword: keyword.hits, similar: similar.hits },
    (key, value) => (typeof value === 'number' ? Number(value.toFixed(2)) : value),
    2
  )
)
 
await narsil.shutdown()
{
  "question": "when do I get my money back",
  "keyword": [],
  "similar": [
    {
      "id": "refund-timing",
      "score": 0.54,
      "document": {
        "title": "How a refund reaches your bank"
      }
    },
    {
      "id": "billing-statement",
      "score": 0.37,
      "document": {
        "title": "Read your monthly billing statement"
      }
    },
    {
      "id": "password-reset",
      "score": 0.29,
      "document": {
        "title": "Reset the password on your account"
      }
    }
  ]
}

The keyword search returns no article, because no article contains the word money or the word back. In the similarity search, the engine puts the refunds article first at 0.54 and the billing statement second at 0.37, which are the two articles about money. The programs in all four languages print the same scores, because each library loads the same model and the four engines use one native core. Compare scores only within one result set, such as 0.54 against the 0.37 below it, and never against a score from another search.

Set a floor under the weakest match

The engine scores every stored vector against the query, so it fills the limit however far the nearest article is from the question. In the results above, the engine gives the password article a score of 0.29 on a question about money, although its subject is passwords. With similarity, or Similarity in Go, you set the score that a hit must reach. The engine drops the hits below that score before it applies limit, so a page can contain fewer hits than limit.

With metric, you choose the comparison. The engine uses cosine, which compares direction alone, when a query sets no metric. Use dotProduct for vectors that your model normalises. euclidean compares distance, which the engine maps to 1 / (1 + distance) before it applies the floor, so with a floor of 0.8, the engine returns the hits at a distance of up to 0.25.

import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const articles = [
  {
    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: '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: 'password-reset',
    title: 'Reset the password on your account',
    body: 'A reset link arrives by email and stays valid for one hour.',
  },
  {
    id: 'mobile-card-payments',
    title: 'Take card payments in the mobile app',
    body: 'The mobile reader pairs over Bluetooth and settles to the same account as the web checkout.',
  },
  {
    id: 'api-key-rotation',
    title: 'Rotate an API key',
    body: 'A new key works at once, and the old key keeps answering for twenty-four hours.',
  },
  {
    id: 'billing-statement',
    title: 'Read your monthly billing statement',
    body: 'The statement lists every charge, every refund, and the fees deducted before payout.',
  },
]
 
const vectors = await embedding.embedBatch(
  articles.map((article) => `${article.title}. ${article.body}`),
  'document'
)
 
const narsil = await createNarsil()
 
await narsil.createIndex('articles', {
  schema: { title: 'string', body: 'string', embedding: 'vector[384]' },
})
 
await narsil.insertBatch(
  'articles',
  articles.map((article, position) => ({ ...article, embedding: vectors[position] }))
)
 
const question = 'when do I get my money back'
 
const keyword = await narsil.query('articles', {
  term: question,
  limit: 3,
  document: { include: ['title'] },
})
 
const similar = await narsil.query('articles', {
  mode: 'vector',
  vector: { field: 'embedding', value: await embedding.embed(question, 'query') }, 
  vector: { field: 'embedding', value: await embedding.embed(question, 'query'), similarity: 0.45 }, 
  limit: 3,
  document: { include: ['title'] },
})
 
console.log(
  JSON.stringify(
    { question, keyword: keyword.hits, similar: similar.hits },
    (key, value) => (typeof value === 'number' ? Number(value.toFixed(2)) : value),
    2
  )
)
 
await narsil.shutdown()
{
  "question": "when do I get my money back",
  "keyword": [],
  "similar": [
    {
      "id": "refund-timing",
      "score": 0.54,
      "document": {
        "title": "How a refund reaches your bank"
      }
    }
  ]
}

With the floor at 0.45, the engine returns only the refunds article, since the billing statement at 0.37 and the password article both fall below the floor. Test that number on your corpus with your model before you settle on it, because a floor that returns the right hits for one question can leave the next question with no hits.

Let a field grow into a graph

Below the promotion threshold of a vector field, the engine answers a search on that field with a brute-force scan, in which it compares the query with every stored vector. Once the field contains more vectors than that threshold, which is 1,024 unless you set another, the engine builds an graph in the background and searches that graph from then on.

The vector maintenance status reports the state of that work, with one entry for each vector field. The insert returns once the engine stores the documents, while the engine goes on building the graph after that. The program below therefore reads the status every 50 milliseconds until no build is in progress and bufferSize reaches 0. The engine answers searches throughout that build, since it scans the vectors outside the graph one by one. bufferSize is the number of those vectors.

The program generates 5,000 titles for a help centre of that size. The counts in the status are the same whatever those titles contain. In Go, the program sends the titles to the model 32 at a time, through hugot's pure Go backend.

import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const ARTICLE_COUNT = 5_000
const SUBJECTS = ['refunds', 'delivery', 'accounts', 'payments', 'billing']
 
const titles = Array.from(
  { length: ARTICLE_COUNT },
  (_unused, position) => `Help centre article ${position} on ${SUBJECTS[position % SUBJECTS.length]}`
)
 
const vectors = await embedding.embedBatch(titles, 'document')
 
const narsil = await createNarsil()
 
await narsil.createIndex('help-centre', {
  schema: { title: 'string', embedding: 'vector[384]' },
})
 
await narsil.insertBatch(
  'help-centre',
  titles.map((title, position) => ({ id: `article-${position}`, title, embedding: vectors[position] }))
)
 
const fieldStatus = () => narsil.vectorMaintenanceStatus('help-centre')[0]
 
while (fieldStatus().building || fieldStatus().bufferSize > 0) {
  await new Promise((resolve) => setTimeout(resolve, 50))
}
 
console.log(JSON.stringify(narsil.vectorMaintenanceStatus('help-centre'), null, 2))
 
await narsil.shutdown()
[
  {
    "fieldName": "embedding",
    "tombstoneRatio": 0,
    "graphCount": 1,
    "bufferSize": 0,
    "building": false,
    "waitingForMemory": false,
    "loadingFromFiles": false,
    "estimatedCompactMs": 0,
    "estimatedOptimizeMs": 0
  }
]

graphCount is 1 once a graph exists, while bufferSize falls to 0 once the graph contains every vector. With hnswConfig, you set the shape of that graph through three options:

  • m is the number of neighbours of each node, which is 16 unless you set another.
  • efConstruction is the breadth of the search during the build, which is 200 unless you set another.
  • metric is the comparison for which the engine builds the graph.

On a query, you can then set efSearch. With a higher efSearch, the engine searches more of the graph, which raises and adds latency. The engine uses efSearch only on a field above its threshold.

When you leave efSearch out of a query, the engine sizes it from the page. It starts from one more than the number of hits up to the end of the page, which is limit plus 1 on a first page. It adds a margin of 50 below 768 dimensions and 75 from 768 to 1,023 dimensions, with no margin at 1,024 dimensions and above. It then searches with that number or 50, whichever is larger.

On a filtered similarity search, the engine applies filterThreshold, a selectivity ratio of 0.03 by default. When a filter matches a smaller share of the field than that ratio, the engine scans the matches alone; when it matches a larger share, the engine searches the graph. In the graph, the engine walks through the documents that fail the filter and collects only the ones that pass it, so it counts only the passing documents towards efSearch.

Choose how the engine stores the vectors, and clear the tombstones

With quantization, you choose how the engine codes each vector that it adds to the graph. In every osq mode, the engine centres the vector on the centroid of the field and then fits an interval to that vector alone. The digit in the name is the number of bits in the code for each dimension, so a code under osq8 contains a byte for each dimension, while a code under osq1 contains one bit. When you leave the mode unset, the engine picks osq4 at 384 dimensions and above, and osq8 below 384. With none, the engine stores no code, so it ranks a search on that field by the full vectors alone.

The engine ranks its candidates by those codes and then re-scores the nearest of them against the full-precision vectors. When you leave oversample out of a query, the engine sets that re-scoring depth from the page size and the dimension of the field. Under osq1 and osq2, it re-scores at least three times the page, because the engine orders the true neighbours less reliably from a one-bit or two-bit code. Under osq4 and osq8, it re-scores at least the page itself. When you set oversample on a query, the engine multiplies the page size by that value in place of those defaults. The engine raises CONFIG_INVALID for a value below 1.

With storage, you choose where the engine stores the full-precision vectors. For a memory field, the engine stores those vectors in memory. For a disk field, the engine stores the codes and the graph in memory, while it loads each full-precision vector from the checkpoint file of the field whenever it re-scores that candidate in a search or you fetch the document. A disk field therefore requires filesystem durability, which is why the program below sets a durability directory. The engine raises CONFIG_INVALID when you ask for disk on an engine without filesystem durability. When you leave storage unset, the engine uses disk if it has filesystem durability, and memory if it doesn't. threshold is the vector count at which the engine starts the build, so with a threshold of 2,048, the engine scans every vector of this field for longer than it does at the default of 1,024.

When you remove or update a vector, the engine leaves a in its place, so that the graph needs no rebuild. However, the engine walks past each tombstone on every search. tombstoneRatio is the share of the nodes in the graph that are tombstones, so that you can see when enough of them build up to slow a search down. When you call compactVectors, the engine drops the tombstones from the graph, and the call returns once that work is over. When you call optimizeVectors, the engine rebuilds the graph from the live vectors, which takes longer than a compaction but restores the search speed. Pass a field to maintain that field alone, or leave the field out to maintain every vector field in the index.

import { rmSync } from 'node:fs'
import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const ARTICLE_COUNT = 5_000
const SUBJECTS = ['refunds', 'delivery', 'accounts', 'payments', 'billing']
 
const titles = Array.from(
  { length: ARTICLE_COUNT },
  (_unused, position) => `Help centre article ${position} on ${SUBJECTS[position % SUBJECTS.length]}`
)
 
const vectors = await embedding.embedBatch(titles, 'document')
 
rmSync('./help-centre-data', { recursive: true, force: true }) 
 
const narsil = await createNarsil() 
const narsil = await createNarsil({ durability: { directory: './help-centre-data' } }) 
 
await narsil.createIndex('help-centre', {
  schema: { title: 'string', embedding: 'vector[384]' },
  vectorPromotion: { threshold: 2_048, quantization: 'osq8', storage: 'disk' }, 
})
 
await narsil.insertBatch(
  'help-centre',
  titles.map((title, position) => ({ id: `article-${position}`, title, embedding: vectors[position] }))
)
 
const fieldStatus = () => narsil.vectorMaintenanceStatus('help-centre')[0]
 
while (fieldStatus().building || fieldStatus().bufferSize > 0) {
  await new Promise((resolve) => setTimeout(resolve, 50))
}
 
for (let position = 0; position < 1_000; position += 1) { 
  await narsil.remove('help-centre', `article-${position}`)
}
 
const withdrawn = fieldStatus()
 
await narsil.compactVectors('help-centre', 'embedding')
 
const compacted = fieldStatus()
 
console.log(JSON.stringify(narsil.vectorMaintenanceStatus('help-centre'), null, 2)) 
console.log(JSON.stringify({ withdrawn, compacted }, null, 2)) 
 
await narsil.shutdown()
{
  "withdrawn": {
    "fieldName": "embedding",
    "tombstoneRatio": 0.2,
    "graphCount": 1,
    "bufferSize": 0,
    "building": false,
    "waitingForMemory": false,
    "loadingFromFiles": false,
    "estimatedCompactMs": 75,
    "estimatedOptimizeMs": 0
  },
  "compacted": {
    "fieldName": "embedding",
    "tombstoneRatio": 0,
    "graphCount": 1,
    "bufferSize": 0,
    "building": false,
    "waitingForMemory": false,
    "loadingFromFiles": false,
    "estimatedCompactMs": 0,
    "estimatedOptimizeMs": 0
  }
}

Once the program removes 1,000 of the 5,000 articles, tombstoneRatio is 0.2. After the compaction, tombstoneRatio is 0, while graphCount is 1, which shows that the graph is in place. For its estimate, the engine allows 0.05 milliseconds of compaction for each tombstone at 256 dimensions, and it scales that figure by the dimension of the field divided by 256. For 1,000 tombstones at 384 dimensions, that formula gives the 75 milliseconds in estimatedCompactMs above. Measure both maintenance calls on your corpus before you schedule either. The counts are the same in every language and under every coding mode and storage mode, since the modes differ only in how and where the engine stores the vectors.

Where to go next

  • Read Hybrid search for the mode in which the engine searches by keyword and by meaning at once and fuses the two rankings into one order.
  • Read Embedding adapters for the adapters that embed your text inside the engine. With one of those adapters, you can insert the text alone and pass text in a query, in place of the value in the queries above.
  • Read Reranking for a second model that scores the question against each of the top hits, after which the engine reorders those hits.
  • Read Persistence and durability for the checkpoint file from which the engine loads the vectors of a disk field.