Search modes

Query suggestions

Offer whole searches that enough different people make and follow with a click, by counting those searches in TypeScript, Python, Go, or Rust and publishing the popular ones to an ordinary index that your application can query.

With popular query suggestions, a search box can offer whole searches, such as 'trail shoes', that other people make and then follow with a click. Your application reports each search that ends in a click, so that the engine can count how many different people search for each phrase. When the engine builds the suggestions, it publishes the phrases that enough people search for to a suggestions index, which is an ordinary index that your application can query in the same way as any other. The next two sections hold one program for a small outdoor shop, written in two steps. Each of their code blocks 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.

Make a key for the IDs of your shoppers

People can type private details into a search box, so the feature stays off until you turn it on for an index. The engine turns it on only once you give it a key of at least 32 bytes, which it uses to scramble the ID of each person before it stores anything. No snapshot or backup holds the key, so keep it in your secret store. Give the engine the same key after every restart, because the engine skips any history file that holds IDs scrambled with another key. This command generates a random key of 64 hexadecimal characters for the examples on this page.

export NARSIL_SUGGESTIONS_KEY="$(openssl rand -hex 32)"

Each program uses only the engine package, which counts the searches and builds the suggestions in all four languages.

pnpm add @delali/narsil

Count the searches that end in a click

Call recordQuery when a person clicks a result, since the engine counts only the searches that you report. The method is record_query in Python and Rust and RecordQuery in Go. Pass the search, the person, and the group with each call. A group is an audience, such as shoppers or staff, that receives a separate set of suggestions, so use one group when every person should see the same suggestions.

The setting that you pass to updateSetting turns the feature on with enabled: true and lists the fields whose text a phrase must match. The engine publishes a phrase only when at least minResults documents match every word of it in those fields. minResults is 5 by default, so the program sets minResults: 2 for a catalogue of nine products. The program stores its data in a new temporary folder, so the engine starts with no history each time that you start the program.

import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { querySuggestions } from '@delali/narsil/query-suggestions'
 
const key = process.env.NARSIL_SUGGESTIONS_KEY
if (key === undefined) {
  throw new Error('Set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes')
}
 
const directory = await mkdtemp(join(tmpdir(), 'catalogue-'))
 
const narsil = await createNarsil({ durability: { directory }, querySuggestions: { key } })
const suggestions = querySuggestions(narsil)
 
await narsil.createIndex('catalogue', { schema: { title: 'string', brand: 'string' } })
 
await narsil.insertBatch('catalogue', [
  { id: 'shoe-01', title: 'Waterproof trail shoes', brand: 'Sato Gear' },
  { id: 'shoe-02', title: 'Lightweight trail shoes', brand: 'Nordvik' },
  { id: 'shoe-03', title: 'Trail shoes with a wide toe box', brand: 'Andes Peak' },
  { id: 'shoe-04', title: 'Road running shoes', brand: 'Nordvik' },
  { id: 'jacket-01', title: 'Packable rain jacket', brand: 'Sato Gear' },
  { id: 'jacket-02', title: 'Insulated rain jacket', brand: 'Okafor Outdoor' },
  { id: 'tent-01', title: 'Two-person trekking tent', brand: 'Andes Peak' },
  { id: 'vest-01', title: 'Trail running vest', brand: 'Okafor Outdoor' },
  { id: 'shorts-01', title: 'Trail running shorts', brand: 'Mwangi Trail Co' },
])
 
await suggestions.updateSetting('catalogue', { enabled: true, fields: ['title', 'brand'], minResults: 2 })
 
const clicks = [
  { query: 'trail shoes', person: 'shopper-1' },
  { query: 'trail shoes', person: 'shopper-2' },
  { query: 'Trail  Shoes', person: 'shopper-3' },
  { query: 'trail shoes', person: 'shopper-4' },
  { query: 'trail shoes', person: 'shopper-5' },
  { query: 'trail shoes', person: 'shopper-1' },
  { query: 'trail running', person: 'shopper-5' },
  { query: 'trail running', person: 'shopper-6' },
  { query: 'trail running', person: 'shopper-7' },
  { query: 'trail running', person: 'shopper-8' },
  { query: 'rain jacket', person: 'shopper-2' },
  { query: 'rain jacket', person: 'shopper-3' },
  { query: 'rain jacket', person: 'shopper-6' },
  { query: 'trekking poles', person: 'shopper-4' },
  { query: 'trekking poles', person: 'shopper-5' },
  { query: 'trekking poles', person: 'shopper-6' },
  { query: 'trekking poles', person: 'shopper-7' },
  { query: 'trail shoes <50!', person: 'shopper-8' },
]
 
const outcomes: Record<string, number> = {}
for (const click of clicks) {
  const { outcome } = await suggestions.recordQuery('catalogue', { ...click, group: 'shoppers' })
  outcomes[outcome] = (outcomes[outcome] ?? 0) + 1
}
 
console.log(JSON.stringify(outcomes, null, 2))
 
await narsil.shutdown()
{
  "recorded": 16,
  "repeat": 1,
  "invalid": 1
}

The engine normalises each search before it counts it, so it counts 'Trail Shoes' as one more search for 'trail shoes'. Since the engine counts a person once for each phrase on each day, it reports repeat for the second 'trail shoes' from shopper-1. It accepts a phrase only when every character of the phrase is a letter, a digit, a space, a hyphen, or an apostrophe, so it reports invalid for trail shoes <50!. It counts at most 100 new phrases from one person on one day, after which it reports person-limit for the 101st.

recordQuery raises QUERY_SUGGESTIONS_NOT_ENABLED on an index that has the feature off. updateSetting raises CONFIG_INVALID when the setting lists a field that is missing from the schema or that has a type other than string or string[].

Publish the phrases that enough people search for

build publishes the popular phrases at once. preview returns the same list without writing anything, because it applies the same checks as build. The engine also builds the suggestions at 03:00 UTC each day by default. The schedule field of the setting accepts any five-field cron expression, or off, while timeZone sets the zone in which the engine interprets that expression.

suggestionsIndexName returns the name of the suggestions index for a group. The program then queries that index with the letters 'tra', in the same way as your application will query it from a search box while a shopper types. With prefix: true, 'tra' matches the start of a word, while with the sort on count, the engine puts the phrases that more people search for first.

import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { querySuggestions } from '@delali/narsil/query-suggestions'
 
const key = process.env.NARSIL_SUGGESTIONS_KEY
if (key === undefined) {
  throw new Error('Set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes')
}
 
const directory = await mkdtemp(join(tmpdir(), 'catalogue-'))
 
const narsil = await createNarsil({ durability: { directory }, querySuggestions: { key } })
const suggestions = querySuggestions(narsil)
 
await narsil.createIndex('catalogue', { schema: { title: 'string', brand: 'string' } })
 
await narsil.insertBatch('catalogue', [
  { id: 'shoe-01', title: 'Waterproof trail shoes', brand: 'Sato Gear' },
  { id: 'shoe-02', title: 'Lightweight trail shoes', brand: 'Nordvik' },
  { id: 'shoe-03', title: 'Trail shoes with a wide toe box', brand: 'Andes Peak' },
  { id: 'shoe-04', title: 'Road running shoes', brand: 'Nordvik' },
  { id: 'jacket-01', title: 'Packable rain jacket', brand: 'Sato Gear' },
  { id: 'jacket-02', title: 'Insulated rain jacket', brand: 'Okafor Outdoor' },
  { id: 'tent-01', title: 'Two-person trekking tent', brand: 'Andes Peak' },
  { id: 'vest-01', title: 'Trail running vest', brand: 'Okafor Outdoor' },
  { id: 'shorts-01', title: 'Trail running shorts', brand: 'Mwangi Trail Co' },
])
 
await suggestions.updateSetting('catalogue', { enabled: true, fields: ['title', 'brand'], minResults: 2 })
 
const clicks = [
  { query: 'trail shoes', person: 'shopper-1' },
  { query: 'trail shoes', person: 'shopper-2' },
  { query: 'Trail  Shoes', person: 'shopper-3' },
  { query: 'trail shoes', person: 'shopper-4' },
  { query: 'trail shoes', person: 'shopper-5' },
  { query: 'trail shoes', person: 'shopper-1' },
  { query: 'trail running', person: 'shopper-5' },
  { query: 'trail running', person: 'shopper-6' },
  { query: 'trail running', person: 'shopper-7' },
  { query: 'trail running', person: 'shopper-8' },
  { query: 'rain jacket', person: 'shopper-2' },
  { query: 'rain jacket', person: 'shopper-3' },
  { query: 'rain jacket', person: 'shopper-6' },
  { query: 'trekking poles', person: 'shopper-4' },
  { query: 'trekking poles', person: 'shopper-5' },
  { query: 'trekking poles', person: 'shopper-6' },
  { query: 'trekking poles', person: 'shopper-7' },
  { query: 'trail shoes <50!', person: 'shopper-8' },
]
 
const outcomes: Record<string, number> = {}
for (const click of clicks) {
  const { outcome } = await suggestions.recordQuery('catalogue', { ...click, group: 'shoppers' })
  outcomes[outcome] = (outcomes[outcome] ?? 0) + 1
}
 
console.log(JSON.stringify(outcomes, null, 2)) 
const preview = await suggestions.preview('catalogue') 
const build = await suggestions.build('catalogue')
const suggestionsIndex = suggestions.suggestionsIndexName('catalogue', 'shoppers')
 
const typed = await narsil.query(suggestionsIndex, { 
  term: 'tra',
  prefix: true,
  termMatch: 'all',
  sort: { count: 'desc' },
})
 
console.log(
  JSON.stringify(
    {
      outcomes,
      preview: preview.entries,
      build: { status: build.status, published: build.published },
      suggestionsIndex,
      typed: typed.hits.map((hit) => hit.document),
    },
    null,
    2
  )
)
 
await narsil.shutdown()
{
  "outcomes": {
    "recorded": 16,
    "repeat": 1,
    "invalid": 1
  },
  "preview": [
    {
      "group": "shoppers",
      "query": "trail shoes",
      "count": 5
    },
    {
      "group": "shoppers",
      "query": "trail running",
      "count": 4
    }
  ],
  "build": {
    "status": "completed",
    "published": 2
  },
  "suggestionsIndex": "catalogue.suggestions.shoppers",
  "typed": [
    {
      "id": "trail shoes",
      "query": "trail shoes",
      "count": 5,
      "origin": "popular"
    },
    {
      "id": "trail running",
      "query": "trail running",
      "count": 4,
      "origin": "popular"
    }
  ]
}

In the program, four people search for 'trekking poles', which meets the default minPeople of 4. However, no product matches both words, so the engine leaves that phrase out. Two products match 'rain jacket'; however, only three people search for it, so the engine leaves that phrase out too. Each document in a suggestions index holds query, count, and origin, with the normalised phrase as its id. count is the number of people who search for the phrase, so 'trail shoes' has a count of 5 although shopper-1 searches for it twice.

Count the clicks of a shopper through the HTTP server

This example serves the index from the TypeScript HTTP server, whose querySuggestions.identify option takes a function, while the code that reports each click to it can use the TypeScript, Python, or Go client. The server takes the person and the group only from the querySuggestions.identify function, because a caller who can choose the person can count one search as many people. In this example, your application passes each shopper's session token in an x-session header. identify looks the token up in the sessions map, where a real server will look it up in your session store. It returns null for a token that the map doesn't hold.

server.ts
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { querySuggestions } from '@delali/narsil/query-suggestions'
import { createServer } from '@delali/narsil/server'
 
const key = process.env.NARSIL_SUGGESTIONS_KEY
if (key === undefined) {
  throw new Error('Set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes')
}
const API_KEY = process.env.NARSIL_API_KEY ?? 'catalogue-key'
 
const sessions = new Map([
  ['session-7f3a', { person: 'shopper-1', group: 'shoppers' }],
  ['session-c21d', { person: 'shopper-2', group: 'shoppers' }],
])
 
const directory = await mkdtemp(join(tmpdir(), 'catalogue-'))
const engine = await createNarsil({ durability: { directory }, querySuggestions: { key }, workers: { enabled: false } })
 
await engine.createIndex('catalogue', { schema: { title: 'string', brand: 'string' } })
await engine.insertBatch('catalogue', [
  { id: 'shoe-01', title: 'Waterproof trail shoes', brand: 'Sato Gear' },
  { id: 'shoe-02', title: 'Lightweight trail shoes', brand: 'Nordvik' },
  { id: 'vest-01', title: 'Trail running vest', brand: 'Okafor Outdoor' },
])
await querySuggestions(engine).updateSetting('catalogue', { enabled: true, fields: ['title', 'brand'], minResults: 2 })
 
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_KEY}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API key as a bearer token.' },
  querySuggestions: {
    identify: (request) => sessions.get(request.headers['x-session'] ?? '') ?? null,
  },
})
 
await server.listen()
console.log('Narsil is listening on http://127.0.0.1:7700')
 
process.once('SIGINT', async () => {
  await server.shutdown()
})

Install uWebSockets.js beside Narsil before you start the server, following the steps on the HTTP server page. Each client below reports four clicks, with only the search in the body and the session token in the x-session header. Start the server again before you start a second client, because the server counts each shopper once for each phrase on each day.

import { createNarsilClient } from '@delali/narsil/client'
 
const API_KEY = process.env.NARSIL_API_KEY ?? 'catalogue-key'
 
const client = createNarsilClient({ url: 'http://127.0.0.1:7700', apiKey: API_KEY })
 
const clicks = [
  { session: 'session-7f3a', query: 'trail shoes' },
  { session: 'session-c21d', query: 'trail shoes' },
  { session: 'session-7f3a', query: 'Trail shoes' },
  { session: 'session-0000', query: 'trail shoes' },
]
 
for (const { session, query } of clicks) {
  const result = await client.recordQuery('catalogue', query, { headers: { 'x-session': session } })
  console.log(session, query, result.outcome)
}
session-7f3a trail shoes recorded
session-c21d trail shoes recorded
session-7f3a Trail shoes repeat
session-0000 trail shoes unidentified

The token session-0000 matches no session, so identify returns null and the server reports unidentified. The server returns status 400 when the body holds a field other than query. When you give the server no identify function, it returns status 404 with QUERY_SUGGESTIONS_NOT_ENABLED for every record request.

Add and ban phrases by hand

addSuggestion adds a phrase to the suggestions index of a group with origin set to manual, and the engine keeps that phrase there through later builds. updateBans replaces the list of banned phrases, while removeQuery adds one phrase to that list. Both methods remove each banned phrase from every suggestions index of the index before they return. Once you ban a phrase, recordQuery reports banned for every click on it. The methods are add_suggestion, update_bans, and remove_query in Python and Rust, and AddSuggestion, UpdateBans, and RemoveQuery in Go.

Check what the history holds before you turn it on

  • The engine keeps the counts in _query-counts/ under the durability directory for retentionDays days, which is 30 by default. It scrambles the IDs of the people; however, the text of each search stays readable, so any copy of the data folder holds the raw searches.
  • A snapshot holds the setting and the ban list. It holds the search history only when you ask for it, with queryHistory: true in TypeScript, query_history=True in Python, SnapshotOptions{QueryHistory: true} in Go, or snapshot_with and query_history: true in Rust.
  • When you turn the feature off, the engine deletes the search history of the index and keeps its suggestions indexes. When you drop the index, the engine drops its suggestions indexes and its history with it.
  • The engine takes every reported click on trust, so under the default minPeople, four people who agree can publish any phrase that matches enough documents. Raise minPeople for an index where a planted phrase can do harm, and check new phrases with preview.
  • A phrase can be a person's name when one of the listed fields holds names, such as an author field, so list only the fields whose values you are content to show as suggestions.
  • Leave the feature off for an index of private lookups, such as a register of phone numbers or account IDs.

Where to go next

  • Read Full-text search for the prefix matching and the term rules that your application uses on a suggestions index.
  • Read Persistence and durability for the directory that holds the search history.
  • Read HTTP server for the server, its onRequest hook, and the routes that the clients call.