okapibm25 1.4.1 → 2.1.0
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 +241 -34
- package/dist/BM25.d.ts +97 -10
- package/dist/BM25.js +333 -45
- package/dist/BM25.js.map +1 -1
- package/package.json +31 -11
- package/BM25.test.ts +0 -109
- package/BM25.ts +0 -90
- package/babel.config.js +0 -6
- package/coverage/BM25.ts.html +0 -350
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -79
- package/coverage/coverage-summary.json +0 -3
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -111
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -170
- package/dist/jest.config.d.ts +0 -7
- package/dist/jest.config.js +0 -9
- package/dist/jest.config.js.map +0 -1
- package/jest.config.ts +0 -6
- package/tsconfig.json +0 -10
package/README.md
CHANGED
|
@@ -1,57 +1,264 @@
|
|
|
1
|
-
#
|
|
1
|
+
# okapibm25
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/okapibm25)
|
|
4
|
+
[](https://github.com/FurkanToprak/OkapiBM25/actions/workflows/ci.yml)
|
|
5
|
+
[](https://www.npmjs.com/package/okapibm25)
|
|
6
|
+
[](https://www.npmjs.com/package/okapibm25)
|
|
7
|
+
[](https://www.npmjs.com/package/okapibm25?activeTab=dependencies)
|
|
8
|
+
[](LICENSE.md)
|
|
2
9
|
|
|
3
10
|

|
|
4
11
|

|
|
5
12
|

|
|
6
13
|

|
|
7
14
|
|
|
15
|
+
Score and rank documents against search keywords with [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25), the ranking function behind most full-text search engines.
|
|
8
16
|
|
|
9
|
-
|
|
17
|
+
- One function. Give it your documents and your keywords, get a score per document.
|
|
18
|
+
- An optional index for searching the same documents many times: about half a millisecond per search on 10,000 documents.
|
|
19
|
+
- No dependencies, 5 kB gzipped.
|
|
20
|
+
- Written in TypeScript, types included.
|
|
21
|
+
- Runs on Node 12 and later, and in browsers through a bundler.
|
|
22
|
+
- Safe with text typed by users: keywords are matched as plain text.
|
|
10
23
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
```
|
|
14
|
-
npm install okapibm25 --save
|
|
15
|
-
```
|
|
16
|
-
## Usage
|
|
24
|
+
```sh
|
|
25
|
+
npm install okapibm25
|
|
17
26
|
```
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
30
|
+
```ts
|
|
18
31
|
import { BM25 } from "okapibm25";
|
|
19
32
|
|
|
20
33
|
const documents = [
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"Each test document will be searched with the keywords specified below.",
|
|
34
|
+
"The quick brown fox jumps over the lazy dog",
|
|
35
|
+
"A quick guide to training your dog",
|
|
36
|
+
"Stock markets fell sharply on Monday",
|
|
25
37
|
];
|
|
26
|
-
const query = ["keywords", "of", "your", "query."];
|
|
27
|
-
// A numerical scoring will be returned.
|
|
28
|
-
const result = BM25(documents, query, { k1: 1.3, b: 0.9 }) as number[];
|
|
29
|
-
console.log(result);
|
|
30
38
|
|
|
39
|
+
const scores = BM25(documents, ["quick", "dog"]);
|
|
40
|
+
// [0.860, 0.958, 0]
|
|
31
41
|
```
|
|
32
|
-
### Sorting
|
|
33
|
-
A recent update allows you to sort your documents. [This works very similar to JavaScript's Array.prototype.sort() function.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
|
|
34
42
|
|
|
35
|
-
|
|
43
|
+
You get one score per document, in the order of `documents`. A higher score means a better match, and a document that contains none of the keywords scores `0`. The second document wins here because both contain the keywords once and it is shorter.
|
|
44
|
+
|
|
45
|
+
Every one of these gives you the same function:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { BM25 } from "okapibm25"; // TypeScript, bundlers, Node ES modules
|
|
49
|
+
import BM25 from "okapibm25"; // TypeScript and bundlers
|
|
50
|
+
const { BM25 } = require("okapibm25"); // CommonJS
|
|
36
51
|
```
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
52
|
+
|
|
53
|
+
## Used by
|
|
54
|
+
- [LlamaIndex](https://www.llamaindex.ai)
|
|
55
|
+
- [LibreChat](https://www.librechat.ai)
|
|
56
|
+
- [Illuma](https://illuma.cx)
|
|
57
|
+
- [Observee](https://www.observee.com/)
|
|
58
|
+
|
|
59
|
+
## Usage
|
|
60
|
+
|
|
61
|
+
### Ranked results
|
|
62
|
+
|
|
63
|
+
Pass a sorter as the fourth argument to get the documents back with their scores, sorted. It works like the function you give to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const ranked = BM25(documents, ["quick", "dog"], undefined, (a, b) => b.score - a.score);
|
|
67
|
+
// [
|
|
68
|
+
// { document: "A quick guide to training your dog", score: 0.958 },
|
|
69
|
+
// { document: "The quick brown fox jumps over the lazy dog", score: 0.860 },
|
|
70
|
+
// { document: "Stock markets fell sharply on Monday", score: 0 },
|
|
71
|
+
// ]
|
|
45
72
|
```
|
|
46
|
-
I've purposely given a schema that lets you sort results by more than just score; you could also sort alphabetically (or by how many times the word 'unicorn' is mentioned, for all I care!) by comparing the documents as well. You can also even ignore scores while sorting!
|
|
47
73
|
|
|
48
|
-
|
|
74
|
+
The sorter receives both the document and its score, so you can sort by score, alphabetically, or by any rule of your own.
|
|
49
75
|
|
|
50
|
-
|
|
51
|
-
An implementation of OkapiBM25 (AKA BM25), a [bag-of-words](https://en.wikipedia.org/wiki/Bag-of-words_model) information retrieval algorithm. [Read up on it here](https://en.wikipedia.org/wiki/Okapi_BM25).
|
|
76
|
+
With a sorter the return type is `{ document: string; score: number }[]`, and without one it is `number[]`. TypeScript knows which one you get, so no cast is needed.
|
|
52
77
|
|
|
53
|
-
|
|
54
|
-
|
|
78
|
+
### Tuning `k1` and `b`
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
BM25(documents, ["quick", "dog"], { k1: 1.5, b: 0.5 });
|
|
82
|
+
// [0.880, 0.953, 0]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- `k1` sets how much it counts when a keyword occurs many times in a document. The default is `1.2`. With `k1: 0` a keyword counts the same whether it occurs once or twenty times.
|
|
86
|
+
- `b` sets how much long documents are penalised. The default is `0.75`. With `b: 0` document length is ignored, and with `b: 1` it counts fully.
|
|
87
|
+
|
|
88
|
+
### Searching for what a user typed
|
|
89
|
+
|
|
90
|
+
Matching is exact, so `"Quick"` does not match `"quick"` and `"dog?"` does not match `"dog"`. To search for text from a search box, lowercase both sides and take the words out of the text:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const toKeywords = (text: string) => text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
94
|
+
|
|
95
|
+
const lowered = documents.map((document) => document.toLowerCase());
|
|
96
|
+
const scores = BM25(lowered, toKeywords("Quick dog?")); // the keywords are ["quick", "dog"]
|
|
97
|
+
|
|
98
|
+
const best = scores
|
|
99
|
+
.map((score, index) => ({ document: documents[index], score }))
|
|
100
|
+
.filter((hit) => hit.score > 0)
|
|
101
|
+
.sort((a, b) => b.score - a.score)
|
|
102
|
+
.slice(0, 10);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The scores line up with `documents` by position, which is how the example gets back to the original text. Common words such as "the" and "is" are keywords like any other. If they drown out the words that matter, remove them from the keywords.
|
|
106
|
+
|
|
107
|
+
An index, described next, does the lowercasing and the splitting for you.
|
|
108
|
+
|
|
109
|
+
### Searching the same documents many times
|
|
110
|
+
|
|
111
|
+
`BM25` reads all the text on every call. When the documents stay the same between searches, build an index once and search that instead:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { createIndex } from "okapibm25";
|
|
115
|
+
|
|
116
|
+
const index = createIndex(documents);
|
|
117
|
+
|
|
118
|
+
const hits = index.search(["Quick", "dog?"]);
|
|
119
|
+
// [
|
|
120
|
+
// { index: 1, document: "A quick guide to training your dog", score: 0.958 },
|
|
121
|
+
// { index: 0, document: "The quick brown fox jumps over the lazy dog", score: 0.860 },
|
|
122
|
+
// ]
|
|
123
|
+
|
|
124
|
+
const top = index.search(["quick", "dog"], { limit: 1, k1: 1.5, b: 0.5 });
|
|
125
|
+
const all = index.scores(["quick", "dog"]);
|
|
126
|
+
// [0.860, 0.958, 0]
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
- `search` returns the documents that contain at least one keyword, best match first. `index` is the position of the document in the array you gave to `createIndex`.
|
|
130
|
+
- `scores` returns one score per document, like `BM25`.
|
|
131
|
+
- The index is a snapshot of the documents. To add or change documents, build a new one.
|
|
132
|
+
|
|
133
|
+
The index uses the same formula as `BM25`, but it matches differently:
|
|
134
|
+
|
|
135
|
+
| | `BM25` | `createIndex` |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| What a keyword matches | Its exact text, anywhere: `"cat"` matches `"concatenate"` | Whole words: `"cat"` matches only the word `cat` |
|
|
138
|
+
| Case | `"Dog"` and `"dog"` differ | Ignored, unless you pass `{ caseSensitive: true }` |
|
|
139
|
+
| Punctuation in a keyword | Part of the text to find: `"c++"` finds `c++` | A gap between words: `"dog?"` finds `dog`, and `"c++"` finds the word `c` |
|
|
140
|
+
| A keyword of several words | Found as a phrase: `"quick guide"` | Each word counts on its own |
|
|
141
|
+
| What a word is | For document length only: a run of `a-z`, `A-Z`, `0-9` and `_` | A run of letters, digits and `_` in any script: `café` and `москва` are words |
|
|
142
|
+
| `k1` and `b` out of range | Used as given | Rejected with an error |
|
|
143
|
+
|
|
144
|
+
The formula is the same. With `{ caseSensitive: true }`, on English text, `index.scores` returns exactly the numbers `BM25` returns for keywords that are single words and occur only as whole words.
|
|
145
|
+
|
|
146
|
+
Languages that are written without spaces, such as Japanese and Chinese, need your own function to split a text into words. It is used for the documents and for the keywords:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
const segmenter = new Intl.Segmenter("ja", { granularity: "word" });
|
|
150
|
+
|
|
151
|
+
const japaneseIndex = createIndex(["犬は速い", "猫は眠る"], {
|
|
152
|
+
tokenizer: (text) =>
|
|
153
|
+
Array.from(segmenter.segment(text))
|
|
154
|
+
.filter((part) => part.isWordLike)
|
|
155
|
+
.map((part) => part.segment),
|
|
156
|
+
});
|
|
157
|
+
japaneseIndex.search(["犬"]); // finds the first document
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
The same option is the place to remove common words or to cut endings off words.
|
|
161
|
+
|
|
162
|
+
## How matching works
|
|
163
|
+
|
|
164
|
+
This is how `BM25` matches. An index made with `createIndex` matches whole words instead; see the table above.
|
|
165
|
+
|
|
166
|
+
- A keyword matches wherever its exact text appears in a document, including inside a longer word: `"cat"` matches `"concatenate"`.
|
|
167
|
+
- Matching is case-sensitive. To ignore case, lowercase your documents and your keywords before calling `BM25`.
|
|
168
|
+
- Keywords are plain text, never regular expressions. `"c++"`, `"(draft)"` and anything else a user types into a search box are safe to pass in as they are.
|
|
169
|
+
- Document length is the number of words, where a word is a run of the characters `a-z`, `A-Z`, `0-9` and `_`.
|
|
170
|
+
- `k1` and `b` default to `1.2` and `0.75`. Both accept `0`.
|
|
171
|
+
|
|
172
|
+
## API
|
|
173
|
+
|
|
174
|
+
### `BM25(documents, keywords, constants?, sorter?)`
|
|
175
|
+
|
|
176
|
+
| Argument | Type | Meaning |
|
|
177
|
+
|---|---|---|
|
|
178
|
+
| `documents` | `readonly string[]` | The texts to score. A document that is not a string scores `0`. |
|
|
179
|
+
| `keywords` | `readonly string[]` | The words or phrases to look for. Each one adds to the score. |
|
|
180
|
+
| `constants` | `{ k1?: number; b?: number }` | Optional. Defaults: `k1` is `1.2`, `b` is `0.75`. |
|
|
181
|
+
| `sorter` | `(a: BMDocument, b: BMDocument) => number` | Optional. When given, the result is sorted with it. |
|
|
182
|
+
|
|
183
|
+
Returns `number[]` without a sorter and `BMDocument[]`, which is `{ document: string; score: number }[]`, with one. Throws a `TypeError` when `documents` or `keywords` is not an array.
|
|
184
|
+
|
|
185
|
+
### `createIndex(documents, options?)`
|
|
186
|
+
|
|
187
|
+
Returns an index of the documents with two methods.
|
|
188
|
+
|
|
189
|
+
| Option | Type | Meaning |
|
|
190
|
+
|---|---|---|
|
|
191
|
+
| `caseSensitive` | `boolean` | Optional. `false` by default: case is ignored. |
|
|
192
|
+
| `tokenizer` | `(text: string) => string[]` | Optional. Splits a text into words. It receives lowercased text unless `caseSensitive` is set. Empty words are dropped. |
|
|
193
|
+
|
|
194
|
+
| Method | Returns |
|
|
195
|
+
|---|---|
|
|
196
|
+
| `index.search(keywords, options?)` | `BMHit[]`, which is `{ index: number; document: string; score: number }[]`: the documents that contain a keyword, best match first. Equal scores keep the order of the documents. |
|
|
197
|
+
| `index.scores(keywords, constants?)` | `number[]`: one score per document, in the order of the documents. |
|
|
198
|
+
|
|
199
|
+
The options of `search` are `k1`, `b` and `limit`, the largest number of results to return. `scores` takes `k1` and `b`.
|
|
200
|
+
|
|
201
|
+
An index is stricter than `BM25` about what it is given:
|
|
202
|
+
|
|
203
|
+
- `k1` must be a finite number of 0 or more, `b` a number from 0 to 1, and `limit` a number of 0 or more. A value of another type throws a `TypeError`, and a number out of range a `RangeError`. Leave an option out to get its default.
|
|
204
|
+
- `documents` and `keywords` must be arrays, and a tokenizer must return an array of strings. Anything else throws a `TypeError`.
|
|
205
|
+
|
|
206
|
+
### Helpers
|
|
207
|
+
|
|
208
|
+
The parts of the calculation are exported too:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import { getWordCount, getTermFrequency, getIDF } from "okapibm25";
|
|
212
|
+
|
|
213
|
+
getWordCount("The quick brown fox"); // 4, the number of words
|
|
214
|
+
getTermFrequency("an", "banana bandana"); // 4, how often the text occurs
|
|
215
|
+
getIDF("dog", documents); // 0.470, higher when fewer documents contain the keyword
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### Types
|
|
219
|
+
|
|
220
|
+
`BMDocument`, `BMConstants`, `BMSorter`, `BMIndex`, `BMIndexOptions`, `BMSearchOptions` and `BMHit` are exported for your own signatures.
|
|
221
|
+
|
|
222
|
+
## Upgrading from 1.x
|
|
223
|
+
|
|
224
|
+
Version 2 matches keywords as plain text. Version 1 treated them as regular expressions, so a keyword such as `dog?` or `c\+\+` gives different scores now. For ordinary keywords the scores are identical to 1.4.1. The cases to check are listed under [Upgrading from 1.x](CHANGELOG.md#upgrading-from-1x) in the changelog.
|
|
225
|
+
|
|
226
|
+
## Speed and limits
|
|
227
|
+
|
|
228
|
+
`BM25` builds no index. Each call reads every document once per keyword, plus once to count its words, so the time grows with the amount of text times the number of keywords. It is about twice as fast as version 1.4.1.
|
|
229
|
+
|
|
230
|
+
`createIndex` reads the documents once. After that a search looks its keywords up and never reads the text again.
|
|
231
|
+
|
|
232
|
+
Measured on an Apple M3 laptop with 10,000 documents of about 200 words each and five keywords:
|
|
233
|
+
|
|
234
|
+
| | Time |
|
|
235
|
+
|---|---|
|
|
236
|
+
| One `BM25` call | 60 ms |
|
|
237
|
+
| `createIndex`, once | 210 ms |
|
|
238
|
+
| `index.search`, best 10 results | 0.5 ms |
|
|
239
|
+
|
|
240
|
+
So `BM25` is the better fit when the documents are different on every call, or when you search them only a few times. The index pays for itself from the fourth search of the same documents. A search takes longer when its keywords are in many documents, because every matching document is ranked. Run `npm run bench` in a clone of the repository to measure it yourself.
|
|
241
|
+
|
|
242
|
+
Everything is kept in memory and nothing is saved to disk. For collections of hundreds of megabytes, use a search engine built for that.
|
|
243
|
+
|
|
244
|
+
## Compatibility
|
|
245
|
+
|
|
246
|
+
- **Node:** 12 and later. The build is ES2015 and CommonJS, and it is loaded on Node 12, 14, 16, 18 and 20 and fully tested on Node 22 and 24 for every change.
|
|
247
|
+
- **TypeScript:** 4.0 and later, with CommonJS, `nodenext` and `bundler` module settings.
|
|
248
|
+
- **Bundlers:** esbuild, webpack and vite are tested for every change.
|
|
249
|
+
- **Stable scores:** the tests compare every change against the published 1.4.1 build, so scores do not move by accident. The changes made on purpose are listed in [CHANGELOG.md](CHANGELOG.md).
|
|
250
|
+
|
|
251
|
+
## Security
|
|
252
|
+
|
|
253
|
+
Keywords are never run as regular expressions, so text from users cannot throw or freeze the process. Releases are published from GitHub Actions with a [provenance attestation](https://docs.npmjs.com/generating-provenance-statements), which links the package on npm to the commit it was built from. To report a security problem, see [SECURITY.md](SECURITY.md).
|
|
55
254
|
|
|
56
255
|
## Contributing
|
|
57
|
-
|
|
256
|
+
|
|
257
|
+
Pull requests are welcome. If this isn't your area, open an issue and I'll get to it. [CONTRIBUTING.md](CONTRIBUTING.md) explains how to run the checks and how a release is made.
|
|
258
|
+
|
|
259
|
+
## License
|
|
260
|
+
|
|
261
|
+
MIT. See [LICENSE.md](LICENSE.md).
|
|
262
|
+
|
|
263
|
+
## Sponsorship
|
|
264
|
+
Consider donating $5 to https://www.unicef.org/ if this has been useful to you.
|
package/dist/BM25.d.ts
CHANGED
|
@@ -1,31 +1,118 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Gets word count. A word is a run of ASCII letters, digits and underscores,
|
|
3
|
+
* the same as the regular expression `\w+`.
|
|
4
|
+
*/
|
|
2
5
|
export declare const getWordCount: (corpus: string) => number;
|
|
3
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* Number of occurrences of a term in a string.
|
|
8
|
+
*
|
|
9
|
+
* The term is matched literally and case-sensitively, and occurrences do not
|
|
10
|
+
* overlap. It is never interpreted as a regular expression, so terms such as
|
|
11
|
+
* `c++` or `(a+)+$` are safe to pass straight from user input. An empty term
|
|
12
|
+
* occurs zero times.
|
|
13
|
+
*/
|
|
4
14
|
export declare const getTermFrequency: (term: string, corpus: string) => number;
|
|
5
15
|
/** Inverse document frequency. */
|
|
6
|
-
export declare const getIDF: (term: string, documents: string[]) => number;
|
|
16
|
+
export declare const getIDF: (term: string, documents: readonly string[]) => number;
|
|
7
17
|
/** Represents a document; useful when sorting results.
|
|
8
18
|
*/
|
|
9
19
|
export interface BMDocument {
|
|
10
|
-
/** The document
|
|
20
|
+
/** The document that was scored. */
|
|
11
21
|
document: string;
|
|
12
|
-
/** The score that the document
|
|
22
|
+
/** The score that the document receives. */
|
|
13
23
|
score: number;
|
|
14
24
|
}
|
|
15
25
|
/** Constants that are free parameters used in BM25, specifically when generating inverse document frequency. */
|
|
16
26
|
export interface BMConstants {
|
|
17
|
-
/** Free parameter. Is 0.75 by default.
|
|
27
|
+
/** Free parameter. Is 0.75 by default. `0` turns length normalization off, `1` applies it fully. */
|
|
18
28
|
b?: number;
|
|
19
|
-
/** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0] */
|
|
29
|
+
/** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0]. `0` ignores how often a term occurs. */
|
|
20
30
|
k1?: number;
|
|
21
31
|
}
|
|
22
32
|
/** If returns positive, the sorting results in secondEl coming before firstEl, else, firstEl comes before secondEL */
|
|
23
|
-
export
|
|
33
|
+
export type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) => number;
|
|
24
34
|
/** Implementation of Okapi BM25 algorithm.
|
|
35
|
+
*
|
|
36
|
+
* Keywords are matched literally and case-sensitively anywhere in a document.
|
|
37
|
+
*
|
|
25
38
|
* @param documents: Collection of documents.
|
|
26
39
|
* @param keywords: query terms.
|
|
27
40
|
* @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.
|
|
28
|
-
* @param
|
|
41
|
+
* @param sorter: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.
|
|
29
42
|
* If this option is provided, the return type will not be an array of scores but an array of documents with their scores.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const scores = BM25(["a cat", "a dog"], ["cat"]); // number[]
|
|
46
|
+
* const ranked = BM25(["a cat", "a dog"], ["cat"], undefined, (x, y) => y.score - x.score); // BMDocument[]
|
|
47
|
+
*/
|
|
48
|
+
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants?: BMConstants): number[];
|
|
49
|
+
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants: BMConstants | undefined, sorter: BMSorter): BMDocument[];
|
|
50
|
+
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants?: BMConstants, sorter?: BMSorter): number[] | BMDocument[];
|
|
51
|
+
/** Options for {@link createIndex}. */
|
|
52
|
+
export interface BMIndexOptions {
|
|
53
|
+
/**
|
|
54
|
+
* Whether `Dog` and `dog` are different words. `false` by default: documents
|
|
55
|
+
* and keywords are lowercased before they are split into words.
|
|
56
|
+
*/
|
|
57
|
+
caseSensitive?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Splits a text into words. It is called for every document and for every
|
|
60
|
+
* keyword, after lowercasing unless `caseSensitive` is set. Empty words are
|
|
61
|
+
* dropped. By default a word is a run of letters, digits and underscores in
|
|
62
|
+
* any script. Pass a tokenizer for languages that are written without
|
|
63
|
+
* spaces, or to remove common words or endings.
|
|
64
|
+
*/
|
|
65
|
+
tokenizer?: (text: string) => string[];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Options for {@link BMIndex.search}. Unlike `BM25`, an index rejects values
|
|
69
|
+
* that cannot give a meaningful score: `k1` must be a finite number of 0 or
|
|
70
|
+
* more and `b` a number from 0 to 1.
|
|
71
|
+
*/
|
|
72
|
+
export interface BMSearchOptions extends BMConstants {
|
|
73
|
+
/** Return at most this many results. All matching documents by default. */
|
|
74
|
+
limit?: number;
|
|
75
|
+
}
|
|
76
|
+
/** A document found by {@link BMIndex.search}. */
|
|
77
|
+
export interface BMHit extends BMDocument {
|
|
78
|
+
/** Position of the document in the array given to {@link createIndex}. */
|
|
79
|
+
index: number;
|
|
80
|
+
}
|
|
81
|
+
/** A searchable index of a fixed set of documents, made by {@link createIndex}. */
|
|
82
|
+
export interface BMIndex {
|
|
83
|
+
/**
|
|
84
|
+
* The documents that contain at least one of the keywords, best match first.
|
|
85
|
+
* Documents with equal scores keep the order they were indexed in.
|
|
86
|
+
*/
|
|
87
|
+
search(keywords: readonly string[], options?: BMSearchOptions): BMHit[];
|
|
88
|
+
/**
|
|
89
|
+
* One score per document, in the order the documents were indexed in. A
|
|
90
|
+
* document that contains none of the keywords scores `0`.
|
|
91
|
+
*/
|
|
92
|
+
scores(keywords: readonly string[], constants?: BMConstants): number[];
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Reads the documents once and builds an index of their words, so that each
|
|
96
|
+
* later search looks words up instead of reading the text again. Worth it when
|
|
97
|
+
* the same documents are searched many times.
|
|
98
|
+
*
|
|
99
|
+
* Matching differs from {@link BM25}: the index matches whole words. `cat`
|
|
100
|
+
* finds the word `cat` and not `concatenate`, and case is ignored unless
|
|
101
|
+
* `caseSensitive` is set. Keywords are split into words the same way as the
|
|
102
|
+
* documents, so the keyword `dog?` finds the word `dog`. The scoring formula
|
|
103
|
+
* and the defaults of `k1` and `b` are those of {@link BM25}.
|
|
104
|
+
*
|
|
105
|
+
* The index is a snapshot. Changing the array afterwards does not change it.
|
|
106
|
+
*
|
|
107
|
+
* @throws TypeError when `documents` is not an array, when `tokenizer` is not
|
|
108
|
+
* a function, or when it returns something other than an array of strings.
|
|
109
|
+
* `search` and `scores` throw a TypeError when `keywords` is not an array or
|
|
110
|
+
* an option is not a number, and a RangeError when an option is out of range.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* const index = createIndex(["A quick dog", "A lazy cat", "Stock markets"]);
|
|
114
|
+
* index.search(["Dog?"]); // [{ index: 0, document: "A quick dog", score: 0.93... }]
|
|
115
|
+
* index.scores(["dog"]); // [0.93..., 0, 0]
|
|
30
116
|
*/
|
|
31
|
-
export
|
|
117
|
+
export declare function createIndex(documents: readonly string[], options?: BMIndexOptions): BMIndex;
|
|
118
|
+
export default BM25;
|