Skip to content

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

import {
function invertedIndex<R, K>(records: Iterable<R>, keysOf: (record: R, id: number) => Iterable<K>): InvertedIndex<K>

Index records by the exact keys returned by keysOf(record, id). The selector is called once per record. Each iterable is consumed once. Keys use Map equality. Repeated keys on one record yield one posting. IDs denote positions in the input at build time. The index retains keys and IDs after construction.

Expected O(n + t) construction time for n records and t yielded keys, excluding the selector's own work. With p distinct record/key associations and k distinct keys, both build workspace and retained storage are O(p + k). A single-key lookup costs expected O(1) plus O(1) per returned ID.

@throws ― {InvertedIndexInvalidInputError} With code MAX_CAPACITY_EXCEEDED when a record ID or the posting count exceeds 2³² − 1, or when the runtime rejects the key table or packed columns. Errors raised by input iterators and the selector propagate to the caller.

invertedIndex
} from 'knotkit/inverted-index'
const
const issues: {
title: string;
labels: string[];
}[]
issues
= [
{
title: string
title
: 'Fix login',
labels: string[]
labels
: ['open', 'urgent'] },
{
title: string
title
: 'Document setup',
labels: never[]
labels
: [] },
{
title: string
title
: 'Fix export',
labels: string[]
labels
: ['urgent', 'urgent'] },
]
const
const index: InvertedIndex<string>
index
=
invertedIndex<{
title: string;
labels: string[];
}, string>(records: Iterable<{
title: string;
labels: string[];
}>, keysOf: (record: {
title: string;
labels: string[];
}, id: number) => Iterable<string>): InvertedIndex<string>

Index records by the exact keys returned by keysOf(record, id). The selector is called once per record. Each iterable is consumed once. Keys use Map equality. Repeated keys on one record yield one posting. IDs denote positions in the input at build time. The index retains keys and IDs after construction.

Expected O(n + t) construction time for n records and t yielded keys, excluding the selector's own work. With p distinct record/key associations and k distinct keys, both build workspace and retained storage are O(p + k). A single-key lookup costs expected O(1) plus O(1) per returned ID.

@throws ― {InvertedIndexInvalidInputError} With code MAX_CAPACITY_EXCEEDED when a record ID or the posting count exceeds 2³² − 1, or when the runtime rejects the key table or packed columns. Errors raised by input iterators and the selector propagate to the caller.

invertedIndex
(
const issues: {
title: string;
labels: string[];
}[]
issues
, (
issue: {
title: string;
labels: string[];
}
issue
) =>
issue: {
title: string;
labels: string[];
}
issue
.
labels: string[]
labels
)
const index: InvertedIndex<string>
index
.
InvertedIndex<string>.size: number

Number of distinct keys. O(1).

size
// 2 distinct labels
const index: InvertedIndex<string>
index
.
InvertedIndex<string>.recordCount: number

Number of input records, including records with no keys. O(1).

recordCount
// 3 issues
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<number>(iterable: Iterable<number> | ArrayLike<number>): number[] (+3 overloads)

Creates an array from an iterable object.

@param ― iterable An iterable object to convert to an array.

from
(
const index: InvertedIndex<string>
index
.
InvertedIndex<string>.postings: (key: string) => IterableIterator<number>

A fresh iterator of matching record IDs, ascending and unique. A missing key yields an empty iterator.

postings
('urgent')) // [0, 2]
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<number>(iterable: Iterable<number> | ArrayLike<number>): number[] (+3 overloads)

Creates an array from an iterable object.

@param ― iterable An iterable object to convert to an array.

from
(
const index: InvertedIndex<string>
index
.
InvertedIndex<string>.postings: (key: string) => IterableIterator<number>

A fresh iterator of matching record IDs, ascending and unique. A missing key yields an empty iterator.

postings
('closed')) // []
const
const titles: string[]
titles
: string[] = []
const index: InvertedIndex<string>
index
.
InvertedIndex<string>.forEachAny: (keys: Iterable<string>, visit: (id: number) => void) => void

Visit each record matching any query key once, in ascending order. An empty query visits nothing. With k query keys and u matching records, uses O(k) temporary space and O(k × (u + 1)) time. Each call owns its cursors. The visitor can query the index recursively. Visitor and iterable errors propagate.

forEachAny
(['urgent', 'open'], (
id: number
id
) =>
const titles: string[]
titles
.
Array<string>.push(...items: string[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@param ― items New elements to add to the array.

push
(
const issues: {
title: string;
labels: string[];
}[]
issues
[
id: number
id
].
title: string
title
))
// titles holds ['Fix login', 'Fix export']
inverted-index.ts
  • 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
{"v":1,"box":[73.5556,94.1597,835.3333,437.3555],"x":{"s":"log","lim":[3.11665831864,1314.2281191],"inv":false,"g":0,"t":"Unique records matching “urgent” or “review”","tk":[[4,"4"],[16,"16"],[64,"64"],[256,"256"],[1024,"1,024"]],"b":10},"y":{"s":"log","lim":[3.02094517113,2711.73408849],"inv":false,"g":0,"tk":[[4,"4"],[16,"16"],[64,"64"],[256,"256"],[2048,"2,048"]],"b":10},"ti":"A tag query reads postings in proportion to its matches; a scan reads all 2,048","a":[{"k":"line","c":"#fffff8","s":"x","d":[4,6,8,11,16,22,32,43,64,86,128,171,256,342,512,683,1024,1366],"p":[105.01,402.72,192.36,372.13,279.72,337.15,367.08,303.32,454.44,268.34,541.8,233.65,629.16,198.66,716.52,163.75,803.88,128.77]},{"k":"line","c":"#1d5fa6","s":"x","d":[4,6,8,11,16,22,32,43,64,86,128,171,256,342,512,683,1024,1366],"p":[105.01,402.72,192.36,372.13,279.72,337.15,367.08,303.32,454.44,268.34,541.8,233.65,629.16,198.66,716.52,163.75,803.88,128.77]},{"k":"line","c":"#fffff8","s":"x","d":[4,4,8,8,16,16,32,32,64,64,128,128,256,256,512,512,1024,1024],"p":[105.01,423.19,192.36,388.2,279.72,353.22,367.08,318.23,454.44,283.25,541.8,248.27,629.16,213.28,716.52,178.3,803.88,143.31]},{"k":"line","c":"#5b6b7c","s":"x","d":[4,4,8,8,16,16,32,32,64,64,128,128,256,256,512,512,1024,1024],"p":[105.01,423.19,192.36,388.2,279.72,353.22,367.08,318.23,454.44,283.25,541.8,248.27,629.16,213.28,716.52,178.3,803.88,143.31]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 4 16 64 256 1,024 Unique records matching “urgent” or “review” 4 16 64 256 2,048 Full scan: 2,048 records this demo: 86 entries for 64 matches Records scanned or posting entries read Posting entries read Unique matches A tag query reads postings in proportion to its matches; a scan reads all 2,048
{"v":1,"box":[73.5556,122.3921,386.0581,437.3555],"x":{"s":"log","lim":[3.11665831864,1314.2281191],"inv":false,"g":0,"t":"Unique records matching “urgent” or “review”","tk":[[4,"4"],[16,"16"],[64,"64"],[256,"256"],[1024,"1,024"]],"b":10},"y":{"s":"log","lim":[3.02094517113,2711.73408849],"inv":false,"g":0,"tk":[[4,"4"],[16,"16"],[64,"64"],[256,"256"],[2048,"2,048"]],"b":10},"ti":"A tag query reads postings in proportion\nto its matches; a scan reads all 2,048","a":[{"k":"line","c":"#fffff8","s":"x","d":[4,6,8,11,16,22,32,43,64,86,128,171,256,342,512,683,1024,1366],"p":[86.46,405.57,122.29,377.5,158.13,345.39,193.97,314.35,229.81,282.24,265.64,250.4,301.48,218.3,337.32,186.26,373.16,154.15]},{"k":"line","c":"#1d5fa6","s":"x","d":[4,6,8,11,16,22,32,43,64,86,128,171,256,342,512,683,1024,1366],"p":[86.46,405.57,122.29,377.5,158.13,345.39,193.97,314.35,229.81,282.24,265.64,250.4,301.48,218.3,337.32,186.26,373.16,154.15]},{"k":"line","c":"#fffff8","s":"x","d":[4,4,8,8,16,16,32,32,64,64,128,128,256,256,512,512,1024,1024],"p":[86.46,424.35,122.29,392.25,158.13,360.14,193.97,328.03,229.81,295.93,265.64,263.82,301.48,231.71,337.32,199.61,373.16,167.5]},{"k":"line","c":"#5b6b7c","s":"x","d":[4,4,8,8,16,16,32,32,64,64,128,128,256,256,512,512,1024,1024],"p":[86.46,424.35,122.29,392.25,158.13,360.14,193.97,328.03,229.81,295.93,265.64,263.82,301.48,231.71,337.32,199.61,373.16,167.5]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 4 16 64 256 1,024 Unique records matching “urgent” or “review” 4 16 64 256 2,048 Full scan: 2,048 records this demo: 86 entries for 64 matches Records scanned or posting entries read Posting entries read Unique matches A tag query reads postings in proportion to its matches; a scan reads all 2,048
  • 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 against knotkit/inverted-index in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
invertedIndexInvertedIndex<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
MemberCost
sizeO(1)
recordCountO(1)
postingsO(1) expected lookup and O(1) per ID
keysO(1) per key
entriesO(1) per key and posting iterator, then O(1) per ID read
forEachAnyO(q × (u + 1)) time and O(q) workspace for q query keys and u visited IDs
InputTypeGet one from
exact keys for each input record and its zero-based ID(record: R, id: number) => Iterable<K>the caller

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
If you need to…Use instead
add or remove associations between queriesMap<K, Set<number>>
match a delimiter-separated key by longest prefixknotkit/trie
combine mutable sets of integer IDsknotkit/bitset

Measured by the suite in 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.

Prompt · knotkit/inverted-index
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/