The BM25 engine over a caller's tokenizer. It imports nothing, so a page can load it; it ranks documents holding any query word (or only those holding every one), matches a stored word whole or by a query word it begins with, and is saved with LexicalIndex.toJSON and restored with LexicalIndex.fromJSON.

A document's score is the sum, over the query's words, of IDF(t) * (tf(t,D) * (k1 + 1)) / (tf(t,D) + k1 * (1 - b + b * |D| / avgdl)), with the Robertson-Walker IDF(t) = log((N - n(t) + 0.5) / (n(t) + 0.5) + 1).

Example

const index = new LexicalIndex({ tokenize: lexicalTokens });
index.addDocument('s1#0', 'The chapters on the budget review');
index.search('chap budg', 10, { prefix: true, match: 'all' }); // the passage s1#0

const saved = JSON.stringify(index.toJSON());
const restored = LexicalIndex.fromJSON(JSON.parse(saved), { tokenize: lexicalTokens });

Hierarchy (view full)

Constructors

Methods

  • Adds a document, replacing one of the same id.

    Parameters

    • id: string
    • text: string
    • Optional metadata: Record<string, unknown>

    Returns void

  • Adds several documents.

    Parameters

    • docs: {
          id: string;
          text: string;
          metadata?: Record<string, unknown>;
      }[]

    Returns void

Properties

k1: number

Term saturation parameter (typical range: 1.2-2.0).

b: number

Document length normalization (0 = none, 1 = full).

documents: Map<string, BM25Document>

Map of document ID to internal document representation.

invertedIndex: Map<string, Map<string, number>>

Each term's documents with the term's count in each: term -> { docId -> termFrequency }.

idf: Map<string, number>

Each term's IDF, recomputed after documents are added or removed.

avgDocLength: number

Average document length across the index (in tokens).

idfDirty: boolean

Whether the IDF cache needs recomputation.

tokenizeText: ((text) => string[])

The tokenizer this index was made with.

Type declaration

    • (text): string[]
    • Parameters

      • text: string

      Returns string[]