@mark1russell7/text 0.0.21 → 0.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/build/bm25.d.ts +55 -0
- package/build/bm25.d.ts.map +1 -0
- package/build/bm25.js +73 -0
- package/build/bm25.js.map +1 -0
- package/package.json +5 -1
- package/src/bm25.ts +91 -0
package/README.md
CHANGED
|
@@ -120,6 +120,22 @@ const corpus = ["The release gate", "The topic graph of the site", "A graph page
|
|
|
120
120
|
rankDocuments(corpus, searchWords("topic graph")); // [{ index: 1, … }, { index: 2, … }, { index: 0, score: 0 }]
|
|
121
121
|
```
|
|
122
122
|
|
|
123
|
+
### A ranked search with BM25
|
|
124
|
+
|
|
125
|
+
The entry `@mark1russell7/text/bm25` ranks the documents of a corpus for a query with Okapi BM25. Since 0.0.23.
|
|
126
|
+
|
|
127
|
+
- `bm25Index(corpus, { k1, b })` makes the index. The index is plain data, so a JSON copy of it gives the same ranks.
|
|
128
|
+
- `bm25Rank(index, query)` gives the score of each document, best first. A tie keeps the order of the corpus.
|
|
129
|
+
- A document and a query are lists of words, for example from `searchWords` of the entry `./search`.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { bm25Index, bm25Rank } from "@mark1russell7/text/bm25";
|
|
133
|
+
import { searchWords } from "@mark1russell7/text/search";
|
|
134
|
+
|
|
135
|
+
const index = bm25Index(["Boil the water.", "Store the water."].map((text) => searchWords(text)));
|
|
136
|
+
bm25Rank(index, searchWords("boil water"))[0]?.index; // 0
|
|
137
|
+
```
|
|
138
|
+
|
|
123
139
|
### A passage in a text
|
|
124
140
|
|
|
125
141
|
The entry `@mark1russell7/text/passage` finds a passage in a text, for example a quote in the text of its source. Since 0.0.18.
|
package/build/bm25.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module has the ranked search Okapi BM25. The index is plain data: a JSON copy of it gives the same ranks.
|
|
3
|
+
* A document and a query are lists of words, for example from `searchWords` of the entry `./search`. Each function has no I/O.
|
|
4
|
+
*/
|
|
5
|
+
/** The format of a BM25 index. A change of the shape of the index changes the format. */
|
|
6
|
+
export declare const BM25_FORMAT = "bm25/1";
|
|
7
|
+
/** The parameters of BM25. */
|
|
8
|
+
export interface Bm25Options {
|
|
9
|
+
/** The saturation of the count of a term: 0 or more. The default is 1.2. A count above approximately `k1` adds little. */
|
|
10
|
+
readonly k1?: number;
|
|
11
|
+
/** The effect of the length of a document: 0 to 1. The default is 0.75. With 0, the length has no effect. */
|
|
12
|
+
readonly b?: number;
|
|
13
|
+
}
|
|
14
|
+
/** The BM25 score of one document of a corpus for a query. */
|
|
15
|
+
export interface Bm25Score {
|
|
16
|
+
/** The position of the document in the corpus. */
|
|
17
|
+
readonly index: number;
|
|
18
|
+
/** The BM25 score: 0 or more, and 0 when the document has no term of the query. */
|
|
19
|
+
readonly score: number;
|
|
20
|
+
}
|
|
21
|
+
/** A BM25 index of a corpus, as plain data. */
|
|
22
|
+
export interface Bm25Index {
|
|
23
|
+
readonly format: typeof BM25_FORMAT;
|
|
24
|
+
readonly k1: number;
|
|
25
|
+
readonly b: number;
|
|
26
|
+
/** The count of the words of each document, in the order of the corpus. */
|
|
27
|
+
readonly lengths: readonly number[];
|
|
28
|
+
/** The mean count of the words of a document. */
|
|
29
|
+
readonly average: number;
|
|
30
|
+
/** For each term, the position of each document that has it and the count of the term in that document, by position. */
|
|
31
|
+
readonly postings: Readonly<Record<string, readonly (readonly [document: number, count: number])[]>>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* This function makes the BM25 index of a corpus.
|
|
35
|
+
*
|
|
36
|
+
* @param corpus - The documents, each as a list of words.
|
|
37
|
+
* @param options - The parameters `k1` and `b`.
|
|
38
|
+
* @returns The index, as plain data.
|
|
39
|
+
* @throws RangeError when `k1` is not a finite number of 0 or more, or `b` is not from 0 to 1.
|
|
40
|
+
*/
|
|
41
|
+
export declare function bm25Index(corpus: readonly (readonly string[])[], options?: Bm25Options): Bm25Index;
|
|
42
|
+
/**
|
|
43
|
+
* This function ranks the documents of a BM25 index for a query.
|
|
44
|
+
*
|
|
45
|
+
* - The weight of a term is ln(1 + (N - df + 0.5) / (df + 0.5)), as Lucene computes it. N is the count of documents, and df the count with the term.
|
|
46
|
+
* - The score of a document is the sum over the different terms of the query of weight × tf × (k1 + 1) / (tf + k1 × (1 - b + b × length / average)).
|
|
47
|
+
* - A term two times in the query counts one time. A term that is not in the index adds 0.
|
|
48
|
+
* - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.
|
|
49
|
+
*
|
|
50
|
+
* @param index - The index, from `bm25Index` or from a JSON copy of it.
|
|
51
|
+
* @param query - The words of the query.
|
|
52
|
+
* @returns The score of each document, best first.
|
|
53
|
+
*/
|
|
54
|
+
export declare function bm25Rank(index: Bm25Index, query: readonly string[]): Bm25Score[];
|
|
55
|
+
//# sourceMappingURL=bm25.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bm25.d.ts","names":[],"sources":["../src/bm25.ts"],"mappings":";;;;;qBAMa;;iBAGI;;WAEN;;WAEA;;;iBAIM;;WAEN;;WAEA;;;iBAIM;WACN,eAAe;WACf;WACA;;WAEA;;WAEA;;WAEA,UAAU,SAAS,mCAAmC,kBAAkB;;;;;;;;;;wBAWnE,UAAU,wCAAwC,UAAS,cAAmB;;;;;;;;;;;;;wBAgC9E,SAAS,OAAO,WAAW,2BAA2B"}
|
package/build/bm25.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// src/bm25.ts
|
|
2
|
+
/**
|
|
3
|
+
* This module has the ranked search Okapi BM25. The index is plain data: a JSON copy of it gives the same ranks.
|
|
4
|
+
* A document and a query are lists of words, for example from `searchWords` of the entry `./search`. Each function has no I/O.
|
|
5
|
+
*/
|
|
6
|
+
/** The format of a BM25 index. A change of the shape of the index changes the format. */
|
|
7
|
+
const BM25_FORMAT = "bm25/1";
|
|
8
|
+
/**
|
|
9
|
+
* This function makes the BM25 index of a corpus.
|
|
10
|
+
*
|
|
11
|
+
* @param corpus - The documents, each as a list of words.
|
|
12
|
+
* @param options - The parameters `k1` and `b`.
|
|
13
|
+
* @returns The index, as plain data.
|
|
14
|
+
* @throws RangeError when `k1` is not a finite number of 0 or more, or `b` is not from 0 to 1.
|
|
15
|
+
*/
|
|
16
|
+
function bm25Index(corpus, options = {}) {
|
|
17
|
+
const k1 = options.k1 ?? 1.2;
|
|
18
|
+
const b = options.b ?? .75;
|
|
19
|
+
if (!(Number.isFinite(k1) && k1 >= 0)) throw new RangeError(`bm25Index: k1 is ${k1}. It must be a finite number of 0 or more.`);
|
|
20
|
+
if (!(b >= 0 && b <= 1)) throw new RangeError(`bm25Index: b is ${b}. It must be from 0 to 1.`);
|
|
21
|
+
const postings = /* @__PURE__ */ new Map();
|
|
22
|
+
corpus.forEach((words, document) => {
|
|
23
|
+
const counts = /* @__PURE__ */ new Map();
|
|
24
|
+
for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1);
|
|
25
|
+
for (const [term, count] of counts) {
|
|
26
|
+
const list = postings.get(term);
|
|
27
|
+
if (list === void 0) postings.set(term, [[document, count]]);
|
|
28
|
+
else list.push([document, count]);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
const lengths = corpus.map((words) => words.length);
|
|
32
|
+
const total = lengths.reduce((sum, length) => sum + length, 0);
|
|
33
|
+
return {
|
|
34
|
+
format: BM25_FORMAT,
|
|
35
|
+
k1,
|
|
36
|
+
b,
|
|
37
|
+
lengths,
|
|
38
|
+
average: lengths.length === 0 ? 0 : total / lengths.length,
|
|
39
|
+
postings: Object.fromEntries(postings)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* This function ranks the documents of a BM25 index for a query.
|
|
44
|
+
*
|
|
45
|
+
* - The weight of a term is ln(1 + (N - df + 0.5) / (df + 0.5)), as Lucene computes it. N is the count of documents, and df the count with the term.
|
|
46
|
+
* - The score of a document is the sum over the different terms of the query of weight × tf × (k1 + 1) / (tf + k1 × (1 - b + b × length / average)).
|
|
47
|
+
* - A term two times in the query counts one time. A term that is not in the index adds 0.
|
|
48
|
+
* - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.
|
|
49
|
+
*
|
|
50
|
+
* @param index - The index, from `bm25Index` or from a JSON copy of it.
|
|
51
|
+
* @param query - The words of the query.
|
|
52
|
+
* @returns The score of each document, best first.
|
|
53
|
+
*/
|
|
54
|
+
function bm25Rank(index, query) {
|
|
55
|
+
const scores = index.lengths.map(() => 0);
|
|
56
|
+
const n = index.lengths.length;
|
|
57
|
+
for (const term of new Set(query)) {
|
|
58
|
+
const list = Object.hasOwn(index.postings, term) ? index.postings[term] : void 0;
|
|
59
|
+
if (list === void 0) continue;
|
|
60
|
+
const weight = Math.log(1 + (n - list.length + .5) / (list.length + .5));
|
|
61
|
+
for (const [document, count] of list) {
|
|
62
|
+
const norm = 1 - index.b + index.b * (index.lengths[document] ?? 0) / index.average;
|
|
63
|
+
scores[document] = (scores[document] ?? 0) + weight * count * (index.k1 + 1) / (count + index.k1 * norm);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return scores.map((score, index) => ({
|
|
67
|
+
index,
|
|
68
|
+
score
|
|
69
|
+
})).sort((a, b) => b.score - a.score);
|
|
70
|
+
}
|
|
71
|
+
export { BM25_FORMAT, bm25Index, bm25Rank };
|
|
72
|
+
|
|
73
|
+
//# sourceMappingURL=bm25.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bm25.js","names":[],"sources":["../src/bm25.ts"],"sourcesContent":["/**\n * This module has the ranked search Okapi BM25. The index is plain data: a JSON copy of it gives the same ranks.\n * A document and a query are lists of words, for example from `searchWords` of the entry `./search`. Each function has no I/O.\n */\n\n/** The format of a BM25 index. A change of the shape of the index changes the format. */\nexport const BM25_FORMAT = \"bm25/1\";\n\n/** The parameters of BM25. */\nexport interface Bm25Options {\n /** The saturation of the count of a term: 0 or more. The default is 1.2. A count above approximately `k1` adds little. */\n readonly k1?: number;\n /** The effect of the length of a document: 0 to 1. The default is 0.75. With 0, the length has no effect. */\n readonly b?: number;\n}\n\n/** The BM25 score of one document of a corpus for a query. */\nexport interface Bm25Score {\n /** The position of the document in the corpus. */\n readonly index: number;\n /** The BM25 score: 0 or more, and 0 when the document has no term of the query. */\n readonly score: number;\n}\n\n/** A BM25 index of a corpus, as plain data. */\nexport interface Bm25Index {\n readonly format: typeof BM25_FORMAT;\n readonly k1: number;\n readonly b: number;\n /** The count of the words of each document, in the order of the corpus. */\n readonly lengths: readonly number[];\n /** The mean count of the words of a document. */\n readonly average: number;\n /** For each term, the position of each document that has it and the count of the term in that document, by position. */\n readonly postings: Readonly<Record<string, readonly (readonly [document: number, count: number])[]>>;\n}\n\n/**\n * This function makes the BM25 index of a corpus.\n *\n * @param corpus - The documents, each as a list of words.\n * @param options - The parameters `k1` and `b`.\n * @returns The index, as plain data.\n * @throws RangeError when `k1` is not a finite number of 0 or more, or `b` is not from 0 to 1.\n */\nexport function bm25Index(corpus: readonly (readonly string[])[], options: Bm25Options = {}): Bm25Index {\n const k1 = options.k1 ?? 1.2;\n const b = options.b ?? 0.75;\n if (!(Number.isFinite(k1) && k1 >= 0)) throw new RangeError(`bm25Index: k1 is ${k1}. It must be a finite number of 0 or more.`);\n if (!(b >= 0 && b <= 1)) throw new RangeError(`bm25Index: b is ${b}. It must be from 0 to 1.`);\n const postings = new Map<string, [number, number][]>();\n corpus.forEach((words, document) => {\n const counts = new Map<string, number>();\n for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1);\n for (const [term, count] of counts) {\n const list = postings.get(term);\n if (list === undefined) postings.set(term, [[document, count]]);\n else list.push([document, count]);\n }\n });\n const lengths = corpus.map((words) => words.length);\n const total = lengths.reduce((sum, length) => sum + length, 0);\n return { format: BM25_FORMAT, k1, b, lengths, average: lengths.length === 0 ? 0 : total / lengths.length, postings: Object.fromEntries(postings) };\n}\n\n/**\n * This function ranks the documents of a BM25 index for a query.\n *\n * - The weight of a term is ln(1 + (N - df + 0.5) / (df + 0.5)), as Lucene computes it. N is the count of documents, and df the count with the term.\n * - The score of a document is the sum over the different terms of the query of weight × tf × (k1 + 1) / (tf + k1 × (1 - b + b × length / average)).\n * - A term two times in the query counts one time. A term that is not in the index adds 0.\n * - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.\n *\n * @param index - The index, from `bm25Index` or from a JSON copy of it.\n * @param query - The words of the query.\n * @returns The score of each document, best first.\n */\nexport function bm25Rank(index: Bm25Index, query: readonly string[]): Bm25Score[] {\n const scores = index.lengths.map(() => 0);\n const n = index.lengths.length;\n for (const term of new Set(query)) {\n const list = Object.hasOwn(index.postings, term) ? index.postings[term] : undefined;\n if (list === undefined) continue;\n const weight = Math.log(1 + (n - list.length + 0.5) / (list.length + 0.5));\n for (const [document, count] of list) {\n const norm = 1 - index.b + (index.b * (index.lengths[document] ?? 0)) / index.average;\n scores[document] = (scores[document] ?? 0) + (weight * count * (index.k1 + 1)) / (count + index.k1 * norm);\n }\n }\n return scores.map((score, index) => ({ index, score })).sort((a, b) => b.score - a.score);\n}\n"],"mappings":";;;;;;AAMA,MAAa,cAAc;;;;;;;;;AAuC3B,SAAgB,UAAU,QAAwC,UAAuB,CAAC,GAAc;CACtG,MAAM,KAAK,QAAQ,MAAM;CACzB,MAAM,IAAI,QAAQ,KAAK;CACvB,IAAI,EAAE,OAAO,SAAS,EAAE,KAAK,MAAM,IAAI,MAAM,IAAI,WAAW,oBAAoB,GAAG,2CAA2C;CAC9H,IAAI,EAAE,KAAK,KAAK,KAAK,IAAI,MAAM,IAAI,WAAW,mBAAmB,EAAE,0BAA0B;CAC7F,MAAM,2BAAW,IAAI,IAAgC;CACrD,OAAO,SAAS,OAAO,aAAa;EAClC,MAAM,yBAAS,IAAI,IAAoB;EACvC,KAAK,MAAM,QAAQ,OAAO,OAAO,IAAI,OAAO,OAAO,IAAI,IAAI,KAAK,KAAK,CAAC;EACtE,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ;GAClC,MAAM,OAAO,SAAS,IAAI,IAAI;GAC9B,IAAI,SAAS,KAAA,GAAW,SAAS,IAAI,MAAM,CAAC,CAAC,UAAU,KAAK,CAAC,CAAC;QACzD,KAAK,KAAK,CAAC,UAAU,KAAK,CAAC;EAClC;CACF,CAAC;CACD,MAAM,UAAU,OAAO,KAAK,UAAU,MAAM,MAAM;CAClD,MAAM,QAAQ,QAAQ,QAAQ,KAAK,WAAW,MAAM,QAAQ,CAAC;CAC7D,OAAO;EAAE,QAAQ;EAAa;EAAI;EAAG;EAAS,SAAS,QAAQ,WAAW,IAAI,IAAI,QAAQ,QAAQ;EAAQ,UAAU,OAAO,YAAY,QAAQ;CAAE;AACnJ;;;;;;;;;;;;;AAcA,SAAgB,SAAS,OAAkB,OAAuC;CAChF,MAAM,SAAS,MAAM,QAAQ,UAAU,CAAC;CACxC,MAAM,IAAI,MAAM,QAAQ;CACxB,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,GAAG;EACjC,MAAM,OAAO,OAAO,OAAO,MAAM,UAAU,IAAI,IAAI,MAAM,SAAS,QAAQ,KAAA;EAC1E,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,SAAS,KAAK,IAAI,KAAK,IAAI,KAAK,SAAS,OAAQ,KAAK,SAAS,GAAI;EACzE,KAAK,MAAM,CAAC,UAAU,UAAU,MAAM;GACpC,MAAM,OAAO,IAAI,MAAM,IAAK,MAAM,KAAK,MAAM,QAAQ,aAAa,KAAM,MAAM;GAC9E,OAAO,aAAa,OAAO,aAAa,KAAM,SAAS,SAAS,MAAM,KAAK,MAAO,QAAQ,MAAM,KAAK;EACvG;CACF;CACA,OAAO,OAAO,KAAK,OAAO,WAAW;EAAE;EAAO;CAAM,EAAE,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC1F"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/text",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.23",
|
|
5
5
|
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf, listOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens and of secrets by their context (findSecretShapes, redactSecretShapes, findSecretShapesInValue, CONTEXT_SHAPES, isSecretName), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf), a scan of HTML for its text and its start tags (scanHtml) with the decode of its character references (decodeReferences) and its plain text (plainText), and a printer of lines and tables to streams that the caller gives (createPrinter).",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"text",
|
|
@@ -84,6 +84,10 @@
|
|
|
84
84
|
"types": "./build/search.d.ts",
|
|
85
85
|
"default": "./build/search.js"
|
|
86
86
|
},
|
|
87
|
+
"./bm25": {
|
|
88
|
+
"types": "./build/bm25.d.ts",
|
|
89
|
+
"default": "./build/bm25.js"
|
|
90
|
+
},
|
|
87
91
|
"./shell": {
|
|
88
92
|
"types": "./build/shell.d.ts",
|
|
89
93
|
"default": "./build/shell.js"
|
package/src/bm25.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module has the ranked search Okapi BM25. The index is plain data: a JSON copy of it gives the same ranks.
|
|
3
|
+
* A document and a query are lists of words, for example from `searchWords` of the entry `./search`. Each function has no I/O.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** The format of a BM25 index. A change of the shape of the index changes the format. */
|
|
7
|
+
export const BM25_FORMAT = "bm25/1";
|
|
8
|
+
|
|
9
|
+
/** The parameters of BM25. */
|
|
10
|
+
export interface Bm25Options {
|
|
11
|
+
/** The saturation of the count of a term: 0 or more. The default is 1.2. A count above approximately `k1` adds little. */
|
|
12
|
+
readonly k1?: number;
|
|
13
|
+
/** The effect of the length of a document: 0 to 1. The default is 0.75. With 0, the length has no effect. */
|
|
14
|
+
readonly b?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The BM25 score of one document of a corpus for a query. */
|
|
18
|
+
export interface Bm25Score {
|
|
19
|
+
/** The position of the document in the corpus. */
|
|
20
|
+
readonly index: number;
|
|
21
|
+
/** The BM25 score: 0 or more, and 0 when the document has no term of the query. */
|
|
22
|
+
readonly score: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A BM25 index of a corpus, as plain data. */
|
|
26
|
+
export interface Bm25Index {
|
|
27
|
+
readonly format: typeof BM25_FORMAT;
|
|
28
|
+
readonly k1: number;
|
|
29
|
+
readonly b: number;
|
|
30
|
+
/** The count of the words of each document, in the order of the corpus. */
|
|
31
|
+
readonly lengths: readonly number[];
|
|
32
|
+
/** The mean count of the words of a document. */
|
|
33
|
+
readonly average: number;
|
|
34
|
+
/** For each term, the position of each document that has it and the count of the term in that document, by position. */
|
|
35
|
+
readonly postings: Readonly<Record<string, readonly (readonly [document: number, count: number])[]>>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* This function makes the BM25 index of a corpus.
|
|
40
|
+
*
|
|
41
|
+
* @param corpus - The documents, each as a list of words.
|
|
42
|
+
* @param options - The parameters `k1` and `b`.
|
|
43
|
+
* @returns The index, as plain data.
|
|
44
|
+
* @throws RangeError when `k1` is not a finite number of 0 or more, or `b` is not from 0 to 1.
|
|
45
|
+
*/
|
|
46
|
+
export function bm25Index(corpus: readonly (readonly string[])[], options: Bm25Options = {}): Bm25Index {
|
|
47
|
+
const k1 = options.k1 ?? 1.2;
|
|
48
|
+
const b = options.b ?? 0.75;
|
|
49
|
+
if (!(Number.isFinite(k1) && k1 >= 0)) throw new RangeError(`bm25Index: k1 is ${k1}. It must be a finite number of 0 or more.`);
|
|
50
|
+
if (!(b >= 0 && b <= 1)) throw new RangeError(`bm25Index: b is ${b}. It must be from 0 to 1.`);
|
|
51
|
+
const postings = new Map<string, [number, number][]>();
|
|
52
|
+
corpus.forEach((words, document) => {
|
|
53
|
+
const counts = new Map<string, number>();
|
|
54
|
+
for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1);
|
|
55
|
+
for (const [term, count] of counts) {
|
|
56
|
+
const list = postings.get(term);
|
|
57
|
+
if (list === undefined) postings.set(term, [[document, count]]);
|
|
58
|
+
else list.push([document, count]);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
const lengths = corpus.map((words) => words.length);
|
|
62
|
+
const total = lengths.reduce((sum, length) => sum + length, 0);
|
|
63
|
+
return { format: BM25_FORMAT, k1, b, lengths, average: lengths.length === 0 ? 0 : total / lengths.length, postings: Object.fromEntries(postings) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* This function ranks the documents of a BM25 index for a query.
|
|
68
|
+
*
|
|
69
|
+
* - The weight of a term is ln(1 + (N - df + 0.5) / (df + 0.5)), as Lucene computes it. N is the count of documents, and df the count with the term.
|
|
70
|
+
* - The score of a document is the sum over the different terms of the query of weight × tf × (k1 + 1) / (tf + k1 × (1 - b + b × length / average)).
|
|
71
|
+
* - A term two times in the query counts one time. A term that is not in the index adds 0.
|
|
72
|
+
* - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.
|
|
73
|
+
*
|
|
74
|
+
* @param index - The index, from `bm25Index` or from a JSON copy of it.
|
|
75
|
+
* @param query - The words of the query.
|
|
76
|
+
* @returns The score of each document, best first.
|
|
77
|
+
*/
|
|
78
|
+
export function bm25Rank(index: Bm25Index, query: readonly string[]): Bm25Score[] {
|
|
79
|
+
const scores = index.lengths.map(() => 0);
|
|
80
|
+
const n = index.lengths.length;
|
|
81
|
+
for (const term of new Set(query)) {
|
|
82
|
+
const list = Object.hasOwn(index.postings, term) ? index.postings[term] : undefined;
|
|
83
|
+
if (list === undefined) continue;
|
|
84
|
+
const weight = Math.log(1 + (n - list.length + 0.5) / (list.length + 0.5));
|
|
85
|
+
for (const [document, count] of list) {
|
|
86
|
+
const norm = 1 - index.b + (index.b * (index.lengths[document] ?? 0)) / index.average;
|
|
87
|
+
scores[document] = (scores[document] ?? 0) + (weight * count * (index.k1 + 1)) / (count + index.k1 * norm);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return scores.map((score, index) => ({ index, score })).sort((a, b) => b.score - a.score);
|
|
91
|
+
}
|