@delali/narsil 0.1.0 → 0.1.2
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 +257 -0
- package/dist/adapters/filesystem.mjs +1 -1
- package/dist/adapters/indexeddb.mjs +1 -1
- package/dist/{chunk-JKIBUPAY.mjs → chunk-7GKPWGCN.mjs} +2 -1
- package/dist/chunk-GVN2W4VA.mjs +570 -0
- package/dist/chunk-HRABJLPB.mjs +64 -0
- package/dist/{chunk-5HXMVMSM.mjs → chunk-LIRVYUQ5.mjs} +1174 -181
- package/dist/direct-executor-DFRFDLFP.mjs +4 -0
- package/dist/index.d.ts +46 -3
- package/dist/index.mjs +1367 -415
- package/dist/vector/hnsw-build-worker.d.ts +37 -0
- package/dist/vector/hnsw-build-worker.mjs +81 -0
- package/dist/workers/entry.mjs +3 -32
- package/package.json +17 -11
- package/dist/chunk-N37VMC62.mjs +0 -18
- package/dist/direct-executor-MQD7JRD4.mjs +0 -3
package/README.md
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
# Narsil
|
|
2
|
+
|
|
3
|
+
[](https://github.com/assetcorp/narsil/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/@delali/narsil)
|
|
5
|
+
[](https://www.npmjs.com/package/@delali/narsil)
|
|
6
|
+
[](https://www.npmjs.com/package/@delali/narsil)
|
|
7
|
+
[](https://github.com/assetcorp/narsil/blob/main/LICENSE)
|
|
8
|
+
|
|
9
|
+
Distributed search, reforged.
|
|
10
|
+
|
|
11
|
+
Narsil is a distributed search engine with full-text, vector, hybrid, and geosearch. It auto-partitions large indexes across workers, serializes them into a cross-language binary format (.nrsl), and merges results back into a single ranked answer. The TypeScript package is the first implementation.
|
|
12
|
+
|
|
13
|
+
> *narsil* is the sword of Elendil in Tolkien's Lord of the Rings, shattered into shards and later reforged. The name maps to the architecture: data shatters into partitions, each shard is independently persisted, and every query reforges them into a unified result.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pnpm add @delali/narsil
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Requires Node.js >= 22.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { Narsil } from '@delali/narsil'
|
|
27
|
+
|
|
28
|
+
const narsil = new Narsil()
|
|
29
|
+
|
|
30
|
+
await narsil.createIndex('products', {
|
|
31
|
+
schema: {
|
|
32
|
+
title: 'string',
|
|
33
|
+
description: 'string',
|
|
34
|
+
price: 'number',
|
|
35
|
+
inStock: 'boolean',
|
|
36
|
+
category: 'enum',
|
|
37
|
+
tags: 'string[]',
|
|
38
|
+
},
|
|
39
|
+
language: 'english',
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
await narsil.insert('products', {
|
|
43
|
+
title: 'Mechanical Keyboard',
|
|
44
|
+
description: 'Cherry MX Brown switches with PBT keycaps and USB-C connection',
|
|
45
|
+
price: 129.99,
|
|
46
|
+
inStock: true,
|
|
47
|
+
category: 'electronics',
|
|
48
|
+
tags: ['peripherals', 'typing', 'mechanical'],
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
const results = await narsil.query('products', {
|
|
52
|
+
term: 'mechanical keyboard',
|
|
53
|
+
filters: {
|
|
54
|
+
inStock: { eq: true },
|
|
55
|
+
price: { lte: 200 },
|
|
56
|
+
},
|
|
57
|
+
boost: { title: 2.0 },
|
|
58
|
+
limit: 10,
|
|
59
|
+
})
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Features
|
|
63
|
+
|
|
64
|
+
### Full-text search
|
|
65
|
+
|
|
66
|
+
BM25 scoring with field boosting, fuzzy matching via bounded Levenshtein distance, exact phrase search, and configurable term matching policies. Specify how many query terms a document must match, set minimum score thresholds, and sort by any field.
|
|
67
|
+
|
|
68
|
+
### Auto-partitioning
|
|
69
|
+
|
|
70
|
+
Indexes split into shards when they grow beyond a configurable threshold. Partition assignment uses FNV-1a hashing for deterministic routing. Background rebalancing redistributes documents across new partitions without blocking queries, using a write-ahead queue for zero-downtime resharding.
|
|
71
|
+
|
|
72
|
+
### Worker isolation
|
|
73
|
+
|
|
74
|
+
Search operations move off the main thread through worker threads (Node.js, Bun) or Web Workers (browser, Deno). The engine starts in direct mode for small indexes and auto-promotes to workers once document counts cross a threshold. You keep using the same API throughout.
|
|
75
|
+
|
|
76
|
+
### Distributed BM25 scoring
|
|
77
|
+
|
|
78
|
+
Three scoring modes handle the partition-skew problem:
|
|
79
|
+
|
|
80
|
+
- **Local**: each partition scores with its own statistics (fastest, default)
|
|
81
|
+
- **DFS (Distributed Frequency Statistics)**: a two-phase query collects global term statistics first, then scores with unified IDF values
|
|
82
|
+
- **Broadcast**: instances share statistics through the invalidation adapter for pre-computed global scoring
|
|
83
|
+
|
|
84
|
+
### Vector search
|
|
85
|
+
|
|
86
|
+
Store and query high-dimensional embeddings with cosine similarity, dot product, or Euclidean distance. Small vector sets use brute-force linear scan. When a field exceeds 10,000 vectors, the engine builds an HNSW graph in the background and swaps the search backend transparently.
|
|
87
|
+
|
|
88
|
+
### Hybrid search
|
|
89
|
+
|
|
90
|
+
Combine full-text BM25 scores with vector similarity scores using weighted alpha blending. A single query searches both text and embeddings, normalizes both score sets to [0,1], and returns a merged ranking.
|
|
91
|
+
|
|
92
|
+
### Geosearch
|
|
93
|
+
|
|
94
|
+
Index latitude/longitude points and query by radius (Haversine or Vincenty distance) or polygon containment (ray casting). High-precision mode switches to Vincenty's iterative formula for long-distance accuracy.
|
|
95
|
+
|
|
96
|
+
### Filters
|
|
97
|
+
|
|
98
|
+
Filter on any indexed field using comparison operators (`eq`, `ne`, `gt`, `lt`, `gte`, `lte`, `between`), string operators (`in`, `nin`, `startsWith`, `endsWith`), array operators (`containsAll`, `matchesAny`, `size`), and presence checks (`exists`, `isEmpty`). Combine filters with explicit `and`, `or`, and `not` boolean combinators.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const results = await narsil.query('products', {
|
|
102
|
+
term: 'wireless',
|
|
103
|
+
filters: {
|
|
104
|
+
or: [
|
|
105
|
+
{ category: { eq: 'electronics' } },
|
|
106
|
+
{ category: { eq: 'accessories' } },
|
|
107
|
+
],
|
|
108
|
+
price: { between: [10, 100] },
|
|
109
|
+
tags: { containsAll: ['bluetooth'] },
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Faceted search
|
|
115
|
+
|
|
116
|
+
Get aggregate value counts alongside search results for building filter UIs.
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
const results = await narsil.query('products', {
|
|
120
|
+
term: 'laptop',
|
|
121
|
+
facets: {
|
|
122
|
+
category: { limit: 10, sort: 'desc' },
|
|
123
|
+
price: { ranges: [{ from: 0, to: 500 }, { from: 500, to: 1000 }, { from: 1000, to: 5000 }] },
|
|
124
|
+
},
|
|
125
|
+
})
|
|
126
|
+
// results.facets.category.values => { electronics: 42, computers: 28, ... }
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Grouping
|
|
130
|
+
|
|
131
|
+
Group results by field values with optional custom reducers.
|
|
132
|
+
|
|
133
|
+
### Match highlighting
|
|
134
|
+
|
|
135
|
+
Get snippets with customizable pre/post tags marking where query terms appear in the original text.
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
const results = await narsil.query('products', {
|
|
139
|
+
term: 'mechanical',
|
|
140
|
+
highlight: {
|
|
141
|
+
fields: ['title', 'description'],
|
|
142
|
+
preTag: '<mark>',
|
|
143
|
+
postTag: '</mark>',
|
|
144
|
+
},
|
|
145
|
+
})
|
|
146
|
+
// hit.highlights.title.snippet => '<mark>Mechanical</mark> Keyboard'
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Term suggestions
|
|
150
|
+
|
|
151
|
+
Get autocomplete suggestions from the index's term dictionary. The API tokenizes the input, extracts the last word, and matches it against stored terms across all partitions. Results are ranked by document frequency.
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const suggestions = await narsil.suggest('products', {
|
|
155
|
+
prefix: 'mech',
|
|
156
|
+
limit: 5,
|
|
157
|
+
})
|
|
158
|
+
// suggestions.terms => [{ term: 'mechan', documentFrequency: 12 }, ...]
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Cursor-based pagination
|
|
162
|
+
|
|
163
|
+
Deep pagination using `searchAfter` cursors that track position across partitions. No offset-based performance degradation for deep result sets.
|
|
164
|
+
|
|
165
|
+
### Results pinning
|
|
166
|
+
|
|
167
|
+
Inject specific documents at fixed positions in the result set, useful for sponsored or editorial content.
|
|
168
|
+
|
|
169
|
+
### Persistence
|
|
170
|
+
|
|
171
|
+
Plug in any storage backend through the persistence adapter interface. Three built-in adapters ship with the package:
|
|
172
|
+
|
|
173
|
+
| Adapter | Import | Environment |
|
|
174
|
+
| --- | --- | --- |
|
|
175
|
+
| Memory | `@delali/narsil/adapters/memory` | All |
|
|
176
|
+
| Filesystem | `@delali/narsil/adapters/filesystem` | Node.js, Bun, Deno |
|
|
177
|
+
| IndexedDB | `@delali/narsil/adapters/indexeddb` | Browser |
|
|
178
|
+
|
|
179
|
+
Persistence uses debounced flushing: dirty partitions serialize on a timer or after a mutation count threshold, whichever fires first. The serialization format is `.nrsl`, a 32-byte header followed by a MessagePack payload. The format is cross-language portable, so a Python or Rust implementation can read and write the same files.
|
|
180
|
+
|
|
181
|
+
### Multi-instance invalidation
|
|
182
|
+
|
|
183
|
+
When multiple instances share the same persistence backend, the invalidation adapter coordinates cache eviction. A filesystem adapter uses marker files for multi-process deployments. A BroadcastChannel adapter handles cross-tab coordination in browsers.
|
|
184
|
+
|
|
185
|
+
### Plugin system
|
|
186
|
+
|
|
187
|
+
Hook into the document and search lifecycle with plugins. Plugins can run before/after insert, remove, update, and search operations, and respond to index creation, partition splits, and worker promotions.
|
|
188
|
+
|
|
189
|
+
### Schema validation
|
|
190
|
+
|
|
191
|
+
Define typed schemas with support for `string`, `number`, `boolean`, `enum`, `geopoint`, `vector[N]`, and array variants (`string[]`, `number[]`, `boolean[]`, `enum[]`). Nested objects up to 4 levels deep. Documents are validated against the schema at insertion time.
|
|
192
|
+
|
|
193
|
+
## Language support
|
|
194
|
+
|
|
195
|
+
Narsil ships with language modules for tokenization, stemming (Snowball algorithm), and stop word removal.
|
|
196
|
+
|
|
197
|
+
### Full support (tokenizer + stemmer + stop words)
|
|
198
|
+
|
|
199
|
+
Arabic, Armenian, Bulgarian, Danish, Dutch, English, Finnish, French, German, Greek, Hindi, Hungarian, Indonesian, Irish, Italian, Nepali, Norwegian, Portuguese, Romanian, Russian, Sanskrit, Serbian, Slovenian, Spanish, Swahili, Swedish, Tamil, Turkish, Ukrainian
|
|
200
|
+
|
|
201
|
+
### CJK support (character n-gram tokenizer + stop words)
|
|
202
|
+
|
|
203
|
+
Chinese (Mandarin), Japanese
|
|
204
|
+
|
|
205
|
+
### African language support
|
|
206
|
+
|
|
207
|
+
Full stemmer support ships for Swahili. Tokenization and stop word support is available for Dagbani, Ewe, Ga, Hausa, Igbo, Twi (Akan), Yoruba, and Zulu.
|
|
208
|
+
|
|
209
|
+
Each language module is a separate entry point, so you only bundle the languages your application needs:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
import '@delali/narsil/languages/french'
|
|
213
|
+
import '@delali/narsil/languages/swahili'
|
|
214
|
+
import '@delali/narsil/languages/twi'
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Search modes
|
|
218
|
+
|
|
219
|
+
| Mode | Method | Scoring |
|
|
220
|
+
| --- | --- | --- |
|
|
221
|
+
| Full-text | `mode: 'fulltext'` | BM25 with field boosting |
|
|
222
|
+
| Vector | `mode: 'vector'` | Cosine similarity, dot product, or Euclidean distance |
|
|
223
|
+
| Hybrid | `mode: 'hybrid'` | Weighted combination of BM25 + vector similarity |
|
|
224
|
+
|
|
225
|
+
## Search quality
|
|
226
|
+
|
|
227
|
+
Ranking quality is measured against the [Cranfield Collection](https://ir-datasets.com/cranfield.html), the foundational information retrieval benchmark created in the 1960s. It contains 1,400 documents and 225 queries with exhaustive human relevance judgments, meaning every query-document pair was scored by domain experts. All engines in this comparison use identical stop words (Lucene English, 35 terms), Porter stemming, and default BM25 parameters.
|
|
228
|
+
|
|
229
|
+
| Engine | nDCG@10 | P@10 | MAP | MRR |
|
|
230
|
+
| --- | ---: | ---: | ---: | ---: |
|
|
231
|
+
| **Narsil 0.1.1** | **0.3739** | **0.2458** | **0.2614** | **0.5638** |
|
|
232
|
+
| Orama 3.1.18 | 0.2911 | 0.1836 | 0.1846 | 0.4821 |
|
|
233
|
+
| MiniSearch 7.2.0 | 0.0077 | 0.0067 | 0.0027 | 0.0139 |
|
|
234
|
+
|
|
235
|
+
**What these metrics mean:**
|
|
236
|
+
|
|
237
|
+
- **nDCG@10** measures whether the most relevant documents appear near the top of the results. A score of 1.0 would mean perfect ranking; 0.0 means no relevant documents in the top 10.
|
|
238
|
+
- **P@10** is the fraction of the top 10 results that are relevant. Narsil averages about 2.5 relevant results in every top-10 list.
|
|
239
|
+
- **MAP** tracks precision at every rank where a relevant document appears. Higher MAP means relevant documents cluster near the top rather than being spread through the result set.
|
|
240
|
+
- **MRR** measures how far a user scrolls to find the first relevant result. Narsil's 0.56 means the first relevant document typically appears at position 2.
|
|
241
|
+
|
|
242
|
+
These scores fall within the expected range for BM25 on standard IR benchmarks (published BM25 baselines on BEIR datasets range from 0.24 to 0.63 nDCG@10). Narsil also runs a [Cranfield regression test](src/__tests__/relevance/cranfield.test.ts) in CI that fails the build if ranking quality drops below calibrated thresholds.
|
|
243
|
+
|
|
244
|
+
Reproduce: `pnpm -C packages/benchmarks bench --tiers quality`
|
|
245
|
+
|
|
246
|
+
## Runtime support (TypeScript)
|
|
247
|
+
|
|
248
|
+
| Runtime | Concurrency | Persistence | Invalidation |
|
|
249
|
+
| --- | --- | --- | --- |
|
|
250
|
+
| Node.js | `worker_threads` | Filesystem | Adapter-based |
|
|
251
|
+
| Bun | `worker_threads` | Filesystem | Adapter-based |
|
|
252
|
+
| Deno | Web Workers | Filesystem | BroadcastChannel |
|
|
253
|
+
| Browser | Web Workers | IndexedDB | BroadcastChannel |
|
|
254
|
+
|
|
255
|
+
## License
|
|
256
|
+
|
|
257
|
+
Apache-2.0
|
|
@@ -26,7 +26,8 @@ var ErrorCodes = {
|
|
|
26
26
|
SEARCH_INVALID_CURSOR: "SEARCH_INVALID_CURSOR",
|
|
27
27
|
LANGUAGE_NOT_SUPPORTED: "LANGUAGE_NOT_SUPPORTED",
|
|
28
28
|
ENVELOPE_VERSION_MISMATCH: "ENVELOPE_VERSION_MISMATCH",
|
|
29
|
-
ENVELOPE_INVALID_MAGIC: "ENVELOPE_INVALID_MAGIC"
|
|
29
|
+
ENVELOPE_INVALID_MAGIC: "ENVELOPE_INVALID_MAGIC",
|
|
30
|
+
PARTITION_CAPACITY_EXCEEDED: "PARTITION_CAPACITY_EXCEEDED"
|
|
30
31
|
};
|
|
31
32
|
var NarsilError = class extends Error {
|
|
32
33
|
code;
|