# knotkit/inverted-index

> Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists

## Use

```ts
import { invertedIndex } from 'knotkit/inverted-index'

const issues = [
  { title: 'Fix login', labels: ['open', 'urgent'] },
  { title: 'Document setup', labels: [] },
  { title: 'Fix export', labels: ['urgent', 'urgent'] },
]
const index = invertedIndex(issues, (issue) => issue.labels)

index.size // 2 distinct labels
index.recordCount // 3 issues
Array.from(index.postings('urgent')) // [0, 2]
Array.from(index.postings('closed')) // []

const titles: string[] = []
index.forEachAny(['urgent', 'open'], (id) => titles.push(issues[id].title))
// titles holds ['Fix login', 'Fix export']
```

## What it solves

* look up all records tagged with an exact key after reading the input once
* visit records carrying any requested tag once, in their original order
* group record positions by feature when a record can supply several features or repeat one

## Try it

ScenarioDefaultReset

* Indexed 2048 records under 2 labels.
* The two posting lists have 86 entries and the union emits 64 unique IDs.
* Build the index once when repeated queries over fixed tags make a full scan wasteful.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/inverted-index/demo.ts) against `knotkit/inverted-index` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                        | Returns            | Does                                                                                                                          |
| ----------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| [`invertedIndex`](/reference/knotkit/inverted-index/functions/invertedindex/) | `InvertedIndex<K>` | Build once from an iterable and its key selector. Every query yields matching zero-based record positions in ascending order. |

Cost per member. Open a row for every operation.

`invertedIndex` 6 members

| Member        | Cost                                                                      |
| ------------- | ------------------------------------------------------------------------- |
| `size`        | O(1)                                                                      |
| `recordCount` | O(1)                                                                      |
| `postings`    | O(1) expected lookup and O(1) per ID                                      |
| `keys`        | O(1) per key                                                              |
| `entries`     | O(1) per key and posting iterator, then O(1) per ID read                  |
| `forEachAny`  | O(q × (u + 1)) time and O(q) workspace for q query keys and u visited IDs |

## What you pass in

| Input                                                  | Type                                     | Get one from |
| ------------------------------------------------------ | ---------------------------------------- | ------------ |
| exact keys for each input record and its zero-based ID | `(record: R, id: number) => Iterable<K>` | `the caller` |

## Errors

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

* `MAX_CAPACITY_EXCEEDED`

## When not to use it

| If you need to…                                   | Use instead                          |
| ------------------------------------------------- | ------------------------------------ |
| add or remove associations between queries        | Map\<K, Set\<number>>                |
| match a delimiter-separated key by longest prefix | [`knotkit/trie`](/modules/trie/)     |
| combine mutable sets of integer IDs               | [`knotkit/bitset`](/modules/bitset/) |

## Performance

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

## Prompt an agent

Prompt · knotkit/inverted-indexCopy prompt

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

Exports:
- `invertedIndex` → `InvertedIndex<K>`: Build once from an iterable and its key selector. Every query yields matching zero-based record positions in ascending order.

Inputs and their sources:
- exact keys for each input record and its zero-based ID: `(record: R, id: number) => Iterable<K>` from `the caller`

Use something else when:
- add or remove associations between queries → Map<K, Set<number>>
- match a delimiter-separated key by longest prefix → knotkit/trie
- combine mutable sets of integer IDs → knotkit/bitset

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

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

## See also

* [API reference](/reference/knotkit/inverted-index/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/inverted-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/inverted-index/knotkit.capability.json)suggest a change to the source record
