Skip to content

knotkit/term-index

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

import {
function termIndex<R>(records: Iterable<R>, termsOf: (record: R, id: number) => readonly string[]): TermIndex

Build a read-only counted index from caller-tokenized documents. The selector runs once per input record. The index retains terms, counts, and document positions. It can discard the source records after construction.

Expected O(n + t) build time for n documents and t token occurrences, plus the selector's work. Build workspace and retained storage are O(n + v + p) for v vocabulary terms and p distinct postings.

@throws ― {TermIndexInvalidInputError} With INVALID_TERMS for a selector result other than an array of strings or MAX_CAPACITY_EXCEEDED when corpus counts or packed storage exceed their bounds. Errors thrown by the input iterable and selector propagate.

termIndex
} from 'knotkit/term-index'
const
const pages: {
title: string;
text: string;
}[]
pages
= [
{
title: string
title
: 'Cache guide',
text: string
text
: 'cache cache invalidation rules' },
{
title: string
title
: 'Setup',
text: string
text
: 'cache setup for teams' },
{
title: string
title
: 'Queues',
text: string
text
: 'queue jobs' },
]
const
const tokenize: (text: string) => RegExpMatchArray | []
tokenize
= (
text: string
text
: string) =>
text: string
text
.
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
().
String.match(matcher: {
[Symbol.match](string: string): RegExpMatchArray | null;
}): RegExpMatchArray | null (+1 overload)

Matches a string or an object that supports being matched against, and returns an array containing the results of that search, or null if no matches are found.

@param ― matcher An object that supports being matched against.

match
(/[\p{L}\p{N}]+/gu) ?? []
const
const index: TermIndex
index
=
termIndex<{
title: string;
text: string;
}>(records: Iterable<{
title: string;
text: string;
}>, termsOf: (record: {
title: string;
text: string;
}, id: number) => readonly string[]): TermIndex

Build a read-only counted index from caller-tokenized documents. The selector runs once per input record. The index retains terms, counts, and document positions. It can discard the source records after construction.

Expected O(n + t) build time for n documents and t token occurrences, plus the selector's work. Build workspace and retained storage are O(n + v + p) for v vocabulary terms and p distinct postings.

@throws ― {TermIndexInvalidInputError} With INVALID_TERMS for a selector result other than an array of strings or MAX_CAPACITY_EXCEEDED when corpus counts or packed storage exceed their bounds. Errors thrown by the input iterable and selector propagate.

termIndex
(
const pages: {
title: string;
text: string;
}[]
pages
, (
page: {
title: string;
text: string;
}
page
) =>
const tokenize: (text: string) => RegExpMatchArray | []
tokenize
(
page: {
title: string;
text: string;
}
page
.
text: string
text
))
const
const hits: readonly TermHit[]
hits
=
const index: TermIndex
index
.
TermIndex.search: (terms: readonly string[], options?: TermSearchOptions) => readonly TermHit[]

Rank documents matching any supplied exact term. Ties in score favor lower IDs. Repeated query terms contribute once. The returned array and hits are independent of the index.

@throws ― {TermIndexInvalidInputError} With INVALID_LIMIT for a limit outside the nonnegative safe integers or INVALID_TERMS for an argument other than an array of strings. Eligibility accessor errors propagate.

search
(
const tokenize: (text: string) => RegExpMatchArray | []
tokenize
('Cache'), {
TermSearchOptions.limit?: number | undefined

Maximum number of hits. Defaults to 10. Zero yields no hits.

limit
: 2 })
const hits: readonly TermHit[]
hits
.
ReadonlyArray<TermHit>.map<string>(callbackfn: (value: TermHit, index: number, array: readonly TermHit[]) => string, thisArg?: any): string[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(({
id: number
id
}) =>
const pages: {
title: string;
text: string;
}[]
pages
[
id: number
id
].
title: string
title
) // ['Cache guide', 'Setup']
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<TermPosting>(iterable: Iterable<TermPosting> | ArrayLike<TermPosting>): TermPosting[] (+3 overloads)

Creates an array from an iterable object.

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

from
(
const index: TermIndex
index
.
TermIndex.postings: (term: string) => IterableIterator<TermPosting>

Iterate the term's counted postings in ascending document ID order.

postings
('cache'))
// [{ id: 0, count: 2 }, { id: 1, count: 1 }]
const
const setupOnly: readonly TermHit[]
setupOnly
=
const index: TermIndex
index
.
TermIndex.search: (terms: readonly string[], options?: TermSearchOptions) => readonly TermHit[]

Rank documents matching any supplied exact term. Ties in score favor lower IDs. Repeated query terms contribute once. The returned array and hits are independent of the index.

@throws ― {TermIndexInvalidInputError} With INVALID_LIMIT for a limit outside the nonnegative safe integers or INVALID_TERMS for an argument other than an array of strings. Eligibility accessor errors propagate.

search
(['cache'], {
TermSearchOptions.limit?: number | undefined

Maximum number of hits. Defaults to 10. Zero yields no hits.

limit
: 1,
TermSearchOptions.eligibleIds?: Pick<ReadonlySet<number>, "has"> | undefined

Restricts hits before ranking. Corpus statistics still include every indexed document.

eligibleIds
: new
var Set: SetConstructor
new <number>(iterable?: Iterable<number> | null | undefined) => Set<number> (+1 overload)
Set
([1]),
})
const setupOnly: readonly TermHit[]
setupOnly
[0].
TermHit.id: number
id
// 1
term-index.ts
  • 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
{"v":1,"box":[268.9097,140.4708,935.3438,445.4349],"x":{"s":"linear","lim":[0,0.774],"inv":false,"g":0,"t":"Score (higher ranks first)","tk":[[0,"0"],[0.2,"0.2"],[0.4,"0.4"],[0.6,"0.6"]]},"y":{"s":"linear","lim":[-0.65,2.65],"inv":false,"g":0,"tk":[[2,"Cache guide: “cache” ×2"],[1,"Setup: “cache” ×1"],[0,"Operations: “cache” ×1"]]},"ti":"BM25 score for “cache”","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[0.506248307526,2],"p":[704.8,200.54],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[0.373659465079,1],"p":[590.64,292.95],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[0.270580991954,0],"p":[501.89,385.37],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#111111"}],"lg":[]} 0 0.2 0.4 0.6 Score (higher ranks first) Cache guide: “cache” ×2 Setup: “cache” ×1 Operations: “cache” ×1 0.51 0.37 0.27 2 hits in 4 words score 0.51; one hit scores 0.37 in 4, 0.27 in 8 BM25 score for “cache” {"v":1,"box":[1005.566,140.4708,1672,445.4349],"x":{"s":"linear","lim":[0,10.32],"inv":false,"g":1,"t":"Words","tk":[[0,"0"],[4,"4"],[8,"8"]]},"y":{"s":"linear","lim":[-0.65,2.65],"inv":false,"g":1,"tk":[[2,""],[1,""],[0,""]]},"ti":"Article length","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[4,2],"p":[1263.87,200.54],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[4,1],"p":[1263.87,292.95],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[8,0],"p":[1522.18,385.37],"r":6.09},{"k":"annotation","c":"#2b2b28"}],"lg":[]} 0 4 8 Words 4 words 4 words 8 words Article length
{"v":1,"box":[268.9097,175.1931,680,498.5592],"x":{"s":"linear","lim":[0,0.774],"inv":false,"g":0,"t":"Score (higher ranks first)","tk":[[0,"0"],[0.2,"0.2"],[0.4,"0.4"],[0.6,"0.6"]]},"y":{"s":"linear","lim":[-0.65,2.65],"inv":false,"g":0,"tk":[[2,"Cache guide: “cache” ×2"],[1,"Setup: “cache” ×1"],[0,"Operations: “cache” ×1"]]},"ti":"BM25 score for “cache”","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[0.506248307526,2],"p":[537.79,238.89],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[0.373659465079,1],"p":[467.37,336.88],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[0.270580991954,0],"p":[412.62,434.87],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#111111"}],"lg":[]} 0 0.2 0.4 0.6 Score (higher ranks first) Cache guide: “cache” ×2 Setup: “cache” ×1 Operations: “cache” ×1 0.51 0.37 0.27 2 hits in 4 words score 0.51; one hit scores 0.37 in 4, 0.27 in 8 BM25 score for “cache” {"v":1,"box":[268.9097,659.6687,680,983.0349],"x":{"s":"linear","lim":[0,10.32],"inv":false,"g":1,"t":"Words","tk":[[0,"0"],[4,"4"],[8,"8"]]},"y":{"s":"linear","lim":[-0.65,2.65],"inv":false,"g":1,"tk":[[2,"Cache guide: “cache” ×2"],[1,"Setup: “cache” ×1"],[0,"Operations: “cache” ×1"]]},"ti":"Article length","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[4,2],"p":[428.25,723.36],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[4,1],"p":[428.25,821.35],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[8,0],"p":[587.58,919.34],"r":6.09},{"k":"annotation","c":"#2b2b28"}],"lg":[]} 0 4 8 Words Cache guide: “cache” ×2 Setup: “cache” ×1 Operations: “cache” ×1 4 words 4 words 8 words Article length
  • 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 against knotkit/term-index.

ExportReturnsDoes
termIndexTermIndexBuild 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
MemberCost
buildO(n + t) expected for n documents and t input tokens
documentLengthO(1)
documentFrequencyO(1) expected
postingsO(1) expected lookup and O(1) per posting
searchO(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
InputTypeGet 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-kPick<ReadonlySet<number>, 'has'>the caller

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
If you need to…Use instead
find records by exact tags without storing occurrence countsknotkit/inverted-index
add or remove postings between searchesMap<string, Map<number, number>>
index raw text with stemming, typo tolerance, or automatic prefix expansionzbsearch

Measured by the suite in packages/term-index/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

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