> Complete content index: https://narsil.sondelali.com/llms.txt

# 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.

URL: https://narsil.sondelali.com/docs/query-suggestions
Section: Search modes
Version: 0.4 (@delali/narsil@0.4.3, latest)

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.

```bash
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.

<CodeGroup sync="language">

```bash title="pnpm" tab="TypeScript"
pnpm add @delali/narsil
```

```bash title="pip" tab="Python"
pip install delali-narsil
```

```bash title="go get" tab="Go"
go get github.com/assetcorp/narsil/packages/go/engine@v0.2.1
```

```bash title="cargo" tab="Rust"
cargo add delali-narsil
```

</CodeGroup>

## 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.

<CodeGroup sync="language">

```ts title="suggestions.ts" tab="TypeScript"
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()
```

```json result open
{
  "recorded": 16,
  "repeat": 1,
  "invalid": 1
}
```

```python title="suggestions.py" tab="Python"
import json
import os
import tempfile

from narsil import Narsil

key = os.environ.get("NARSIL_SUGGESTIONS_KEY")
if key is None:
    raise SystemExit("Set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes")

directory = tempfile.mkdtemp(prefix="catalogue-")

PRODUCTS = [
    {"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"},
]

CLICKS = [
    ("trail shoes", "shopper-1"),
    ("trail shoes", "shopper-2"),
    ("Trail  Shoes", "shopper-3"),
    ("trail shoes", "shopper-4"),
    ("trail shoes", "shopper-5"),
    ("trail shoes", "shopper-1"),
    ("trail running", "shopper-5"),
    ("trail running", "shopper-6"),
    ("trail running", "shopper-7"),
    ("trail running", "shopper-8"),
    ("rain jacket", "shopper-2"),
    ("rain jacket", "shopper-3"),
    ("rain jacket", "shopper-6"),
    ("trekking poles", "shopper-4"),
    ("trekking poles", "shopper-5"),
    ("trekking poles", "shopper-6"),
    ("trekking poles", "shopper-7"),
    ("trail shoes <50!", "shopper-8"),
]

with Narsil({"durability": {"directory": directory}, "querySuggestions": {"key": key}}) as narsil:
    suggestions = narsil.query_suggestions

    narsil.create_index("catalogue", {"schema": {"title": "string", "brand": "string"}})
    narsil.insert_batch("catalogue", PRODUCTS)

    suggestions.update_setting("catalogue", {"enabled": True, "fields": ["title", "brand"], "minResults": 2})

    outcomes = {}
    for query, person in CLICKS:
        result = suggestions.record_query("catalogue", {"query": query, "person": person, "group": "shoppers"})
        outcomes[result["outcome"]] = outcomes.get(result["outcome"], 0) + 1

    print(json.dumps(outcomes, indent=2))
```

```json result open
{
  "recorded": 16,
  "repeat": 1,
  "invalid": 1
}
```

```go title="main.go" tab="Go"
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/assetcorp/narsil/packages/go/engine"
)

var products = []map[string]any{
	{"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"},
}

var clicks = [][2]string{
	{"trail shoes", "shopper-1"},
	{"trail shoes", "shopper-2"},
	{"Trail  Shoes", "shopper-3"},
	{"trail shoes", "shopper-4"},
	{"trail shoes", "shopper-5"},
	{"trail shoes", "shopper-1"},
	{"trail running", "shopper-5"},
	{"trail running", "shopper-6"},
	{"trail running", "shopper-7"},
	{"trail running", "shopper-8"},
	{"rain jacket", "shopper-2"},
	{"rain jacket", "shopper-3"},
	{"rain jacket", "shopper-6"},
	{"trekking poles", "shopper-4"},
	{"trekking poles", "shopper-5"},
	{"trekking poles", "shopper-6"},
	{"trekking poles", "shopper-7"},
	{"trail shoes <50!", "shopper-8"},
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	key := os.Getenv("NARSIL_SUGGESTIONS_KEY")
	if key == "" {
		return errors.New("set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes")
	}

	directory, err := os.MkdirTemp("", "catalogue-")
	if err != nil {
		return err
	}

	narsil, err := engine.New(ctx, engine.Config{
		Durability:       &engine.DurabilityConfig{Directory: directory},
		QuerySuggestions: &engine.QuerySuggestionsConfig{Key: []byte(key)},
	})
	if err != nil {
		return err
	}
	defer narsil.Shutdown(ctx)
	suggestions := narsil.QuerySuggestions()

	err = narsil.CreateIndex(ctx, "catalogue", engine.IndexConfig{
		Schema: engine.Schema{"title": engine.FieldString, "brand": engine.FieldString},
	})
	if err != nil {
		return err
	}

	documents := make([]*engine.Document, len(products))
	for position, product := range products {
		documents[position] = engine.DocumentFromMap(product)
	}
	if _, err := narsil.InsertBatch(ctx, "catalogue", documents, engine.InsertOptions{}); err != nil {
		return err
	}

	err = suggestions.UpdateSetting(ctx, "catalogue", engine.QuerySuggestionsSetting{
		Enabled:    true,
		Fields:     []string{"title", "brand"},
		MinResults: engine.Some(2),
	})
	if err != nil {
		return err
	}

	outcomes := map[engine.RecordQueryOutcome]int{}
	for _, click := range clicks {
		result, err := suggestions.RecordQuery(ctx, "catalogue", engine.RecordedQuery{
			Query:  click[0],
			Person: click[1],
			Group:  "shoppers",
		})
		if err != nil {
			return err
		}
		outcomes[result.Outcome]++
	}

	fmt.Println("outcomes:", outcomes)
	return nil
}
```

```text result open
outcomes: map[invalid:1 recorded:16 repeat:1]
```

```rust title="src/main.rs" tab="Rust"
use std::collections::BTreeMap;
use std::{env, process};

use narsil::{
    DurabilityConfig, IndexConfig, Narsil, NarsilConfig, QuerySuggestionsConfig, QuerySuggestionsSetting,
    RecordedQuery, Value, parse_json,
};

const PRODUCTS: &str = r#"[
  { "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" }
]"#;

const CLICKS: [(&str, &str); 18] = [
    ("trail shoes", "shopper-1"),
    ("trail shoes", "shopper-2"),
    ("Trail  Shoes", "shopper-3"),
    ("trail shoes", "shopper-4"),
    ("trail shoes", "shopper-5"),
    ("trail shoes", "shopper-1"),
    ("trail running", "shopper-5"),
    ("trail running", "shopper-6"),
    ("trail running", "shopper-7"),
    ("trail running", "shopper-8"),
    ("rain jacket", "shopper-2"),
    ("rain jacket", "shopper-3"),
    ("rain jacket", "shopper-6"),
    ("trekking poles", "shopper-4"),
    ("trekking poles", "shopper-5"),
    ("trekking poles", "shopper-6"),
    ("trekking poles", "shopper-7"),
    ("trail shoes <50!", "shopper-8"),
];

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = env::var("NARSIL_SUGGESTIONS_KEY")
        .map_err(|_| "set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes")?;
    let directory = env::temp_dir().join(format!("catalogue-{}", process::id()));

    let narsil = Narsil::open(NarsilConfig {
        durability: Some(DurabilityConfig { directory: Some(directory), ..DurabilityConfig::default() }),
        query_suggestions: Some(QuerySuggestionsConfig { key: key.into_bytes() }),
        ..NarsilConfig::default()
    })?;
    let suggestions = narsil.query_suggestions();

    narsil.create_index(
        "catalogue",
        IndexConfig {
            schema: parse_json(r#"{ "title": "string", "brand": "string" }"#)?,
            ..IndexConfig::default()
        },
    )?;

    let mut documents = Vec::new();
    if let Value::Array(products) = parse_json(PRODUCTS)? {
        for product in products {
            if let Value::Object(document) = product {
                documents.push(document);
            }
        }
    }
    narsil.insert_batch("catalogue", documents)?;

    suggestions.update_setting(
        "catalogue",
        &QuerySuggestionsSetting {
            enabled: true,
            fields: vec!["title".into(), "brand".into()],
            min_results: Some(2),
            ..QuerySuggestionsSetting::default()
        },
    )?;

    let mut outcomes = BTreeMap::new();
    for (query, person) in CLICKS {
        let result = suggestions.record_query(
            "catalogue",
            &RecordedQuery { query: query.into(), person: person.into(), group: "shoppers".into() },
        )?;
        *outcomes.entry(result.outcome.as_str()).or_insert(0) += 1;
    }

    println!("outcomes: {outcomes:?}");
    Ok(())
}
```

```text result open
outcomes: {"invalid": 1, "recorded": 16, "repeat": 1}
```

</CodeGroup>

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.

<CodeGroup sync="language">

```ts title="suggestions.ts" tab="TypeScript"
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)) // [!code --]
const preview = await suggestions.preview('catalogue') // [!code ++:3]
const build = await suggestions.build('catalogue')
const suggestionsIndex = suggestions.suggestionsIndexName('catalogue', 'shoppers')

const typed = await narsil.query(suggestionsIndex, { // [!code ++:21]
  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()
```

```json result open
{
  "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"
    }
  ]
}
```

```python title="suggestions.py" tab="Python"
import json
import os
import tempfile

from narsil import Narsil

key = os.environ.get("NARSIL_SUGGESTIONS_KEY")
if key is None:
    raise SystemExit("Set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes")

directory = tempfile.mkdtemp(prefix="catalogue-")

PRODUCTS = [
    {"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"},
]

CLICKS = [
    ("trail shoes", "shopper-1"),
    ("trail shoes", "shopper-2"),
    ("Trail  Shoes", "shopper-3"),
    ("trail shoes", "shopper-4"),
    ("trail shoes", "shopper-5"),
    ("trail shoes", "shopper-1"),
    ("trail running", "shopper-5"),
    ("trail running", "shopper-6"),
    ("trail running", "shopper-7"),
    ("trail running", "shopper-8"),
    ("rain jacket", "shopper-2"),
    ("rain jacket", "shopper-3"),
    ("rain jacket", "shopper-6"),
    ("trekking poles", "shopper-4"),
    ("trekking poles", "shopper-5"),
    ("trekking poles", "shopper-6"),
    ("trekking poles", "shopper-7"),
    ("trail shoes <50!", "shopper-8"),
]

with Narsil({"durability": {"directory": directory}, "querySuggestions": {"key": key}}) as narsil:
    suggestions = narsil.query_suggestions

    narsil.create_index("catalogue", {"schema": {"title": "string", "brand": "string"}})
    narsil.insert_batch("catalogue", PRODUCTS)

    suggestions.update_setting("catalogue", {"enabled": True, "fields": ["title", "brand"], "minResults": 2})

    outcomes = {}
    for query, person in CLICKS:
        result = suggestions.record_query("catalogue", {"query": query, "person": person, "group": "shoppers"})
        outcomes[result["outcome"]] = outcomes.get(result["outcome"], 0) + 1

    print(json.dumps(outcomes, indent=2))  # [!code --]
    preview = suggestions.preview("catalogue")  # [!code ++:21]
    build = suggestions.build("catalogue")
    suggestions_index = suggestions.suggestions_index_name("catalogue", "shoppers")

    typed = narsil.query(
        suggestions_index,
        {"term": "tra", "prefix": True, "termMatch": "all", "sort": {"count": "desc"}},
    )

    print(
        json.dumps(
            {
                "outcomes": outcomes,
                "preview": preview["entries"],
                "build": {"status": build["status"], "published": build["published"]},
                "suggestionsIndex": suggestions_index,
                "typed": [hit["document"] for hit in typed["hits"]],
            },
            indent=2,
        )
    )
```

```json result open
{
  "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"
    }
  ]
}
```

```go title="main.go" tab="Go"
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/assetcorp/narsil/packages/go/engine"
)

var products = []map[string]any{
	{"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"},
}

var clicks = [][2]string{
	{"trail shoes", "shopper-1"},
	{"trail shoes", "shopper-2"},
	{"Trail  Shoes", "shopper-3"},
	{"trail shoes", "shopper-4"},
	{"trail shoes", "shopper-5"},
	{"trail shoes", "shopper-1"},
	{"trail running", "shopper-5"},
	{"trail running", "shopper-6"},
	{"trail running", "shopper-7"},
	{"trail running", "shopper-8"},
	{"rain jacket", "shopper-2"},
	{"rain jacket", "shopper-3"},
	{"rain jacket", "shopper-6"},
	{"trekking poles", "shopper-4"},
	{"trekking poles", "shopper-5"},
	{"trekking poles", "shopper-6"},
	{"trekking poles", "shopper-7"},
	{"trail shoes <50!", "shopper-8"},
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	key := os.Getenv("NARSIL_SUGGESTIONS_KEY")
	if key == "" {
		return errors.New("set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes")
	}

	directory, err := os.MkdirTemp("", "catalogue-")
	if err != nil {
		return err
	}

	narsil, err := engine.New(ctx, engine.Config{
		Durability:       &engine.DurabilityConfig{Directory: directory},
		QuerySuggestions: &engine.QuerySuggestionsConfig{Key: []byte(key)},
	})
	if err != nil {
		return err
	}
	defer narsil.Shutdown(ctx)
	suggestions := narsil.QuerySuggestions()

	err = narsil.CreateIndex(ctx, "catalogue", engine.IndexConfig{
		Schema: engine.Schema{"title": engine.FieldString, "brand": engine.FieldString},
	})
	if err != nil {
		return err
	}

	documents := make([]*engine.Document, len(products))
	for position, product := range products {
		documents[position] = engine.DocumentFromMap(product)
	}
	if _, err := narsil.InsertBatch(ctx, "catalogue", documents, engine.InsertOptions{}); err != nil {
		return err
	}

	err = suggestions.UpdateSetting(ctx, "catalogue", engine.QuerySuggestionsSetting{
		Enabled:    true,
		Fields:     []string{"title", "brand"},
		MinResults: engine.Some(2),
	})
	if err != nil {
		return err
	}

	outcomes := map[engine.RecordQueryOutcome]int{}
	for _, click := range clicks {
		result, err := suggestions.RecordQuery(ctx, "catalogue", engine.RecordedQuery{
			Query:  click[0],
			Person: click[1],
			Group:  "shoppers",
		})
		if err != nil {
			return err
		}
		outcomes[result.Outcome]++
	}

	fmt.Println("outcomes:", outcomes)
	// [!code ++:37]

	preview, err := suggestions.Preview(ctx, "catalogue", engine.Optional[int]{})
	if err != nil {
		return err
	}
	build, err := suggestions.Build(ctx, "catalogue")
	if err != nil {
		return err
	}
	suggestionsIndex, err := suggestions.SuggestionsIndexName("catalogue", "shoppers")
	if err != nil {
		return err
	}

	typed, err := narsil.Query(ctx, suggestionsIndex, engine.QueryParams{
		Term:      "tra",
		Prefix:    true,
		TermMatch: engine.MatchAllTerms(),
		Sort:      []engine.SortField{{Field: "count", Direction: engine.SortDescending}},
	})
	if err != nil {
		return err
	}

	fmt.Println("preview:")
	for _, entry := range preview.Entries {
		fmt.Printf("  %s %q %d\n", entry.Group, entry.Query, entry.Count)
	}
	fmt.Println("build:", build.Status, "published", build.Published)
	fmt.Println("suggestions index:", suggestionsIndex)
	fmt.Println("typed:")
	for _, hit := range typed.Hits {
		query, _ := hit.Document.Get("query")
		count, _ := hit.Document.Get("count")
		origin, _ := hit.Document.Get("origin")
		fmt.Printf("  %q %v %v\n", query, count, origin)
	}
	return nil
}
```

```text result open
outcomes: map[invalid:1 recorded:16 repeat:1]
preview:
  shoppers "trail shoes" 5
  shoppers "trail running" 4
build: completed published 2
suggestions index: catalogue.suggestions.shoppers
typed:
  "trail shoes" 5 popular
  "trail running" 4 popular
```

```rust title="src/main.rs" tab="Rust"
use std::collections::BTreeMap;
use std::{env, process};

use narsil::{
    DurabilityConfig, IndexConfig, Narsil, NarsilConfig, QuerySuggestionsConfig, QuerySuggestionsSetting, // [!code --:2]
    RecordedQuery, Value, parse_json,
    DurabilityConfig, IndexConfig, Map, Narsil, NarsilConfig, QueryParams, QuerySuggestionsConfig, // [!code ++:2]
    QuerySuggestionsSetting, RecordedQuery, SortDirection, SortField, TermMatch, Value, parse_json,
};

const PRODUCTS: &str = r#"[
  { "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" }
]"#;

const CLICKS: [(&str, &str); 18] = [
    ("trail shoes", "shopper-1"),
    ("trail shoes", "shopper-2"),
    ("Trail  Shoes", "shopper-3"),
    ("trail shoes", "shopper-4"),
    ("trail shoes", "shopper-5"),
    ("trail shoes", "shopper-1"),
    ("trail running", "shopper-5"),
    ("trail running", "shopper-6"),
    ("trail running", "shopper-7"),
    ("trail running", "shopper-8"),
    ("rain jacket", "shopper-2"),
    ("rain jacket", "shopper-3"),
    ("rain jacket", "shopper-6"),
    ("trekking poles", "shopper-4"),
    ("trekking poles", "shopper-5"),
    ("trekking poles", "shopper-6"),
    ("trekking poles", "shopper-7"),
    ("trail shoes <50!", "shopper-8"),
];

fn text(document: &Map, name: &str) -> String { // [!code ++:8]
    match document.get(name) {
        Some(Value::String(value)) => value.clone(),
        Some(Value::Number(value)) => value.to_string(),
        _ => String::new(),
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = env::var("NARSIL_SUGGESTIONS_KEY")
        .map_err(|_| "set NARSIL_SUGGESTIONS_KEY to a secret of at least 32 bytes")?;
    let directory = env::temp_dir().join(format!("catalogue-{}", process::id()));

    let narsil = Narsil::open(NarsilConfig {
        durability: Some(DurabilityConfig { directory: Some(directory), ..DurabilityConfig::default() }),
        query_suggestions: Some(QuerySuggestionsConfig { key: key.into_bytes() }),
        ..NarsilConfig::default()
    })?;
    let suggestions = narsil.query_suggestions();

    narsil.create_index(
        "catalogue",
        IndexConfig {
            schema: parse_json(r#"{ "title": "string", "brand": "string" }"#)?,
            ..IndexConfig::default()
        },
    )?;

    let mut documents = Vec::new();
    if let Value::Array(products) = parse_json(PRODUCTS)? {
        for product in products {
            if let Value::Object(document) = product {
                documents.push(document);
            }
        }
    }
    narsil.insert_batch("catalogue", documents)?;

    suggestions.update_setting(
        "catalogue",
        &QuerySuggestionsSetting {
            enabled: true,
            fields: vec!["title".into(), "brand".into()],
            min_results: Some(2),
            ..QuerySuggestionsSetting::default()
        },
    )?;

    let mut outcomes = BTreeMap::new();
    for (query, person) in CLICKS {
        let result = suggestions.record_query(
            "catalogue",
            &RecordedQuery { query: query.into(), person: person.into(), group: "shoppers".into() },
        )?;
        *outcomes.entry(result.outcome.as_str()).or_insert(0) += 1;
    }

    println!("outcomes: {outcomes:?}");
    // [!code ++:35]

    let preview = suggestions.preview("catalogue", None)?;
    let build = suggestions.build("catalogue")?;
    let suggestions_index = suggestions.suggestions_index_name("catalogue", "shoppers")?;

    let typed = narsil.query(
        &suggestions_index,
        &QueryParams {
            term: Some("tra".into()),
            prefix: Some(true),
            term_match: Some(TermMatch::All),
            sort: Some(vec![SortField {
                field: "count".into(),
                direction: SortDirection::Desc,
                mode: None,
            }]),
            ..QueryParams::default()
        },
    )?;

    println!("preview:");
    for entry in &preview.entries {
        println!("  {} {:?} {}", entry.group, entry.query, entry.count);
    }
    println!("build: {} published {}", build.status.as_str(), build.published);
    println!("suggestions index: {suggestions_index}");
    println!("typed:");
    for hit in &typed.hits {
        println!(
            "  {:?} {} {}",
            text(&hit.document, "query"),
            text(&hit.document, "count"),
            text(&hit.document, "origin")
        );
    }
    Ok(())
}
```

```text result open
outcomes: {"invalid": 1, "recorded": 16, "repeat": 1}
preview:
  shoppers "trail shoes" 5
  shoppers "trail running" 4
build: completed published 2
suggestions index: catalogue.suggestions.shoppers
typed:
  "trail shoes" 5 popular
  "trail running" 4 popular
```

</CodeGroup>

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](/docs/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.

```ts title="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](/docs/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.

<CodeGroup sync="language">

```ts title="record.ts" tab="TypeScript"
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)
}
```

```text result open
session-7f3a trail shoes recorded
session-c21d trail shoes recorded
session-7f3a Trail shoes repeat
session-0000 trail shoes unidentified
```

```python title="record.py" tab="Python"
import os

from narsil_client import NarsilClient

API_KEY = os.environ.get("NARSIL_API_KEY", "catalogue-key")

CLICKS = [
    ("session-7f3a", "trail shoes"),
    ("session-c21d", "trail shoes"),
    ("session-7f3a", "Trail shoes"),
    ("session-0000", "trail shoes"),
]

with NarsilClient("http://127.0.0.1:7700", api_key=API_KEY) as client:
    for session, query in CLICKS:
        result = client.record_query("catalogue", {"query": query}, headers={"x-session": session})
        print(session, query, result.outcome)
```

```text result open
session-7f3a trail shoes recorded
session-c21d trail shoes recorded
session-7f3a Trail shoes repeat
session-0000 trail shoes unidentified
```

```go title="main.go" tab="Go"
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	narsil "github.com/assetcorp/narsil/packages/go"
)

var clicks = [][2]string{
	{"session-7f3a", "trail shoes"},
	{"session-c21d", "trail shoes"},
	{"session-7f3a", "Trail shoes"},
	{"session-0000", "trail shoes"},
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	apiKey := os.Getenv("NARSIL_API_KEY")
	if apiKey == "" {
		apiKey = "catalogue-key"
	}

	client, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7700"}, APIKey: apiKey})
	if err != nil {
		return err
	}
	defer client.CloseIdleConnections()

	for _, click := range clicks {
		result, err := client.RecordQuery(ctx, "catalogue", narsil.RecordQueryBody{Query: click[1]},
			narsil.WithHeader("x-session", click[0]))
		if err != nil {
			return err
		}
		fmt.Println(click[0], click[1], result.Outcome)
	}
	return nil
}
```

```text result open
session-7f3a trail shoes recorded
session-c21d trail shoes recorded
session-7f3a Trail shoes repeat
session-0000 trail shoes unidentified
```

</CodeGroup>

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](/docs/full-text-search) for the prefix matching and the term rules that your application uses on a suggestions index.
- Read [Persistence and durability](/docs/persistence-and-durability) for the directory that holds the search history.
- Read [HTTP server](/docs/http-server) for the server, its `onRequest` hook, and the routes that the clients call.
