# knotkit/term-index

> Indexes tokenized documents with exact term counts and ranks matching document IDs by BM25

## Use

```ts
import { termIndex } from 'knotkit/term-index'

const pages = [
  { title: 'Cache guide', text: 'cache cache invalidation rules' },
  { title: 'Setup', text: 'cache setup for teams' },
  { title: 'Queues', text: 'queue jobs' },
]

const tokenize = (text: string) => text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []
const index = termIndex(pages, (page) => tokenize(page.text))

const hits = index.search(tokenize('Cache'), { limit: 2 })
hits.map(({ id }) => pages[id].title) // ['Cache guide', 'Setup']
Array.from(index.postings('cache'))
// [{ id: 0, count: 2 }, { id: 1, count: 1 }]

const setupOnly = index.search(['cache'], {
  limit: 1,
  eligibleIds: new Set([1]),
})
setupOnly[0].id // 1
```

## What it solves

* rank documents matching any of a set of exact tokens
* restrict ranked search to eligible document IDs without changing corpus statistics
* read term counts per document and document frequencies without scanning the corpus

## Worked example

* Query “cache” matches 3 of 4 help articles.
* Cache guide — 2 of 4 words match. BM25 0.506.
* Setup — 1 of 4 words match. BM25 0.374.
* Operations — 1 of 8 words match. BM25 0.271.
* Cache guide wins on repeated matches. Setup beats Operations with the same match count in fewer words.
* A one-hit search returns Cache guide overall and Operations in the operations section.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/term-index/demo.ts) against `knotkit/term-index`.

## API

| Export                                                            | Returns     | Does                                                                                                                           |
| ----------------------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
| [`termIndex`](/reference/knotkit/term-index/functions/termindex/) | `TermIndex` | Build once from an iterable of documents and a token selector. Search exact terms with BM25 and return scored input positions. |

Cost per member. Open a row for every operation.

`termIndex` 5 members

| Member              | Cost                                                                                                                                                             |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `build`             | O(n + t) expected for n documents and t input tokens                                                                                                             |
| `documentLength`    | O(1)                                                                                                                                                             |
| `documentFrequency` | O(1) expected                                                                                                                                                    |
| `postings`          | O(1) expected lookup and O(1) per posting                                                                                                                        |
| `search`            | O(q + u log(u + 1) + p + c log(k + 1)) expected for q query tokens, u unique known terms, p visited postings, c eligible matching documents, and k retained hits |

## What you pass in

| Input                                                       | Type                                           | Get one from |
| ----------------------------------------------------------- | ---------------------------------------------- | ------------ |
| one array of tokens for each document and its zero-based ID | `(record: R, id: number) => readonly string[]` | `the caller` |
| optional document eligibility, checked before top-k         | `Pick<ReadonlySet<number>, 'has'>`             | `the caller` |

## Errors

Every error this module throws is `TermIndexInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `INVALID_LIMIT` `INVALID_TERMS` `MAX_CAPACITY_EXCEEDED`

## When not to use it

| If you need to…                                                             | Use instead                                          |
| --------------------------------------------------------------------------- | ---------------------------------------------------- |
| find records by exact tags without storing occurrence counts                | [`knotkit/inverted-index`](/modules/inverted-index/) |
| add or remove postings between searches                                     | Map\<string, Map\<number, number>>                   |
| index raw text with stemming, typo tolerance, or automatic prefix expansion | zbsearch                                             |

## Performance

Measured by the suite in [`packages/term-index/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/term-index/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/term-indexCopy prompt

```
Use knotkit/term-index for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/term-index'.

Exports:
- `termIndex` → `TermIndex`: Build once from an iterable of documents and a token selector. Search exact terms with BM25 and return scored input positions.

Inputs and their sources:
- one array of tokens for each document and its zero-based ID: `(record: R, id: number) => readonly string[]` from `the caller`
- optional document eligibility, checked before top-k: `Pick<ReadonlySet<number>, 'has'>` from `the caller`

Use something else when:
- find records by exact tags without storing occurrence counts → knotkit/inverted-index
- add or remove postings between searches → Map<string, Map<number, number>>
- index raw text with stemming, typo tolerance, or automatic prefix expansion → zbsearch

Errors are TermIndexInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/term-index.md
Types: node_modules/knotkit/term-index/ and https://knotkit.jkomyno.dev/reference/knotkit/term-index/
```

## See also

* [API reference](/reference/knotkit/term-index/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/term-index/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/term-index/knotkit.capability.json)suggest a change to the source record
