@kedem/okdb 3.0.0 → 3.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/CHANGELOG.md +114 -3
- package/README.md +72 -36
- package/bin/okdb +1 -1
- package/docs/auth-and-sync.md +30 -24
- package/docs/auth-permissions.md +5 -4
- package/docs/c-bridge.md +94 -0
- package/docs/change-log.md +79 -36
- package/docs/data-model.md +35 -9
- package/docs/deployment.md +42 -38
- package/docs/diagnostics.md +61 -125
- package/docs/embeddings.md +143 -51
- package/docs/encryption.md +132 -0
- package/docs/files.md +64 -27
- package/docs/fts.md +48 -23
- package/docs/functions.md +109 -56
- package/docs/getting-started.md +121 -9
- package/docs/http-api.md +66 -11
- package/docs/http-cluster.md +80 -88
- package/docs/index.md +33 -15
- package/docs/indexes.md +53 -17
- package/docs/licensing.md +19 -5
- package/docs/logging.md +11 -22
- package/docs/manifest.json +6 -3
- package/docs/migration.md +41 -16
- package/docs/pipelines.md +111 -46
- package/docs/plugins.md +47 -15
- package/docs/process-registry.md +23 -24
- package/docs/processors.md +26 -23
- package/docs/querying.md +102 -29
- package/docs/queue.md +165 -51
- package/docs/resolved-fields.md +24 -1
- package/docs/subscriptions.md +4 -4
- package/docs/sync.md +9 -6
- package/docs/time-machine.md +52 -14
- package/docs/transactions.md +63 -15
- package/docs/ttl.md +34 -13
- package/docs/upgrade-2.0.md +32 -15
- package/docs/upgrade-2.1.md +10 -12
- package/docs/upgrade-3.0.md +144 -0
- package/docs/views.md +165 -61
- package/index.js +1 -1
- package/native/linux-x64-gnu/okdb +0 -0
- package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
- package/native-loader.js +1 -1
- package/okdb-native.js +1 -1
- package/package.json +1 -1
- package/public/features/files/parts/files-blob-status.ok.js +1 -1
- package/types/environment.d.ts +32 -11
- package/types/errors.d.ts +20 -0
- package/types/features/admin.d.ts +3 -5
- package/types/features/api.d.ts +5 -7
- package/types/features/embeddings.d.ts +8 -7
- package/types/features/engines.d.ts +9 -1
- package/types/features/files.d.ts +2 -1
- package/types/features/fts.d.ts +3 -3
- package/types/features/functions.d.ts +14 -8
- package/types/features/pipelines.d.ts +10 -10
- package/types/features/queue.d.ts +15 -10
- package/types/features/sync.d.ts +7 -0
- package/types/features/time-machine.d.ts +3 -0
- package/types/index.d.ts +3 -0
- package/types/okdb.d.ts +70 -7
- package/types/options.d.ts +12 -8
- package/docs/OKDB-ARCHITECTURE.md +0 -1061
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Encryption & Key Rotation
|
|
2
|
+
|
|
3
|
+
okdb encrypts a store at rest when you give it an `encryptionKey`. With a key, nothing under the database folder holds your data in
|
|
4
|
+
clear: the environments, their full-text indexes, time-machine history, file blobs (their names too) and vector-search snapshots
|
|
5
|
+
are all encrypted. Without a key, the files are plain.
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
const OKDB = require('@kedem/okdb');
|
|
9
|
+
|
|
10
|
+
const db = new OKDB('./secure-db', { encryptionKey: '0123456789abcdef0123456789abcdef' }); // 32 characters
|
|
11
|
+
await db.open();
|
|
12
|
+
await db.env('default').ensureType('notes');
|
|
13
|
+
await db.env('default').put('notes', 'n1', { text: 'only readable with the key' });
|
|
14
|
+
await db.close();
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Two layers of keys
|
|
18
|
+
|
|
19
|
+
Your key (the **user key**) never encrypts data directly. Every encrypted environment has its own random 32-byte **data key**;
|
|
20
|
+
everything in the environment is encrypted with keys derived from it (its LMDB files, its blob and snapshot files, the names of its
|
|
21
|
+
blobs). The data key is stored only wrapped (AES-256-GCM) by the user key, in a small file next to the environment's data:
|
|
22
|
+
`<env-path>/keyring`. An environment without encryption has no keyring.
|
|
23
|
+
|
|
24
|
+
This is what makes rotation cheap and safe:
|
|
25
|
+
|
|
26
|
+
- **changing the user key** rewraps the data keys — no data is rewritten, nothing closes;
|
|
27
|
+
- **re-encrypting** gives an environment a new data key and rewrites its files under it (also how encryption is added to, or
|
|
28
|
+
removed from, an environment).
|
|
29
|
+
|
|
30
|
+
## Where keys come from
|
|
31
|
+
|
|
32
|
+
- `encryptionKey` — the instance key: it covers `~system` and every environment without a key of its own.
|
|
33
|
+
- `createEnvironment(name, { encryptionKey })` — an environment's own key. A static key is kept in the environment registry (as
|
|
34
|
+
it always was) — in clear unless the instance itself has a key, since the registry lives in `~system`; a **function** key is
|
|
35
|
+
never stored, so prefer one for an environment-only key.
|
|
36
|
+
- A key may be a **function** (sync or async) returning the key. okdb calls it at `open()` and again whenever another process
|
|
37
|
+
changes the key, so a key held in a vault or a secrets manager is fetched fresh:
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
const OKDB = require('@kedem/okdb');
|
|
41
|
+
|
|
42
|
+
const fetchKey = async () => '0123456789abcdef0123456789abcdef'; // e.g. read from your secrets manager
|
|
43
|
+
const db = new OKDB('./fn-key-db', { encryptionKey: fetchKey });
|
|
44
|
+
await db.open();
|
|
45
|
+
await db.createEnvironment('vault', { encryptionKey: async () => 'fedcba9876543210fedcba9876543210' });
|
|
46
|
+
await db.close();
|
|
47
|
+
|
|
48
|
+
// an environment created with a function key needs it again on the next open
|
|
49
|
+
const again = new OKDB('./fn-key-db', {
|
|
50
|
+
encryptionKey: fetchKey,
|
|
51
|
+
encryptionKeys: { vault: async () => 'fedcba9876543210fedcba9876543210' },
|
|
52
|
+
});
|
|
53
|
+
await again.open();
|
|
54
|
+
await again.openEnv('vault');
|
|
55
|
+
await again.close();
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Keys live in process memory only: never in a log line, a bus datagram or shared memory.
|
|
59
|
+
|
|
60
|
+
## Changing the key
|
|
61
|
+
|
|
62
|
+
```js
|
|
63
|
+
const OKDB = require('@kedem/okdb');
|
|
64
|
+
|
|
65
|
+
const db = new OKDB('./rotate-db', { encryptionKey: '0123456789abcdef0123456789abcdef' });
|
|
66
|
+
await db.open();
|
|
67
|
+
await db.changeEncryptionKey({ to: 'abcdefabcdefabcdefabcdefabcdef12' }); // the instance key (and ~system)
|
|
68
|
+
await db.createEnvironment('vault', { encryptionKey: 'fedcba9876543210fedcba9876543210' });
|
|
69
|
+
await db.changeEncryptionKey({ env: 'vault', to: '00112233445566778899aabbccddeeff' }); // one environment's own key
|
|
70
|
+
await db.close();
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`changeEncryptionKey({ env?, to })` rewraps the data keys of the environment (with its sub-environments that use the same key) or,
|
|
74
|
+
without `env`, of everything that uses the instance key. The old key no longer opens the store. Other processes keep working —
|
|
75
|
+
they hold their data keys in memory: a process with a function key fetches the new key; a process with a static key logs that its
|
|
76
|
+
next open needs the new key. `to` may be a function too. CLI: `okdb rekey --key <current> --to <new> [--env <name>]` (or
|
|
77
|
+
`OKDB_NEW_ENCRYPTION_KEY` instead of `--to`).
|
|
78
|
+
|
|
79
|
+
Changing the user key does not change the data keys: someone who kept the old key **and** an old copy of a keyring can still read
|
|
80
|
+
the data of that copy. To revoke that, re-encrypt.
|
|
81
|
+
|
|
82
|
+
## Re-encrypting an environment
|
|
83
|
+
|
|
84
|
+
```js
|
|
85
|
+
const OKDB = require('@kedem/okdb');
|
|
86
|
+
|
|
87
|
+
const db = new OKDB('./reencrypt-db', { encryptionKey: '0123456789abcdef0123456789abcdef' });
|
|
88
|
+
await db.open();
|
|
89
|
+
await db.createEnvironment('plain', { encryptionKey: null }); // explicitly unencrypted
|
|
90
|
+
await db.env('default').ensureType('t');
|
|
91
|
+
await db.env('default').put('t', 'k', { v: 1 });
|
|
92
|
+
|
|
93
|
+
await db.reencrypt({ env: 'default' }); // a new data key, the same user key
|
|
94
|
+
await db.reencrypt({ env: 'plain', to: 'fedcba9876543210fedcba9876543210' }); // add encryption
|
|
95
|
+
await db.reencrypt({ env: 'plain', to: null }); // remove it again
|
|
96
|
+
await db.close();
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`reencrypt({ env, to? })` rewrites the environment (and its embeddings sub-environments) under a new data key — under the same
|
|
100
|
+
user key (`to` omitted), a new one (`to`: a key or a function), or without encryption (`to: null`). It runs in the calling process
|
|
101
|
+
and coordinates every other process on the store by itself:
|
|
102
|
+
|
|
103
|
+
1. it takes the environment's exclusive lease (no compaction or second re-encryption meanwhile) and records its progress in
|
|
104
|
+
`<env-path>/rekey.json`;
|
|
105
|
+
2. every process closes the environment. **Reads and writes on it wait** — they continue when it is back (after
|
|
106
|
+
`OKDB_REKEY_WAIT_MS`, 10 minutes by default, a call fails with the retryable `REKEY_IN_PROGRESS`);
|
|
107
|
+
3. once no process holds the environment's files, it rewrites the environment, its full-text index, time-machine history and
|
|
108
|
+
blobs under the new key, and drops its vector snapshots (they rebuild);
|
|
109
|
+
4. it switches the keyring and signals; every process reopens the environment by itself, unwrapping the new data key with the user
|
|
110
|
+
key it holds. When encryption was just added, a process needs the key (a function key, or `encryptionKeys`); one without it logs
|
|
111
|
+
an error and keeps the environment closed.
|
|
112
|
+
|
|
113
|
+
A crash is safe: the next process that needs the environment sees the interrupted run and finishes it. If other processes do not
|
|
114
|
+
let go of the environment within `OKDB_REKEY_PEER_WAIT_MS` (60 s), nothing is changed and the call fails with the retryable
|
|
115
|
+
`REKEY_PEERS_BUSY`. `~system` cannot be re-encrypted in place (`REKEY_SYSTEM_UNSUPPORTED`); change its key with
|
|
116
|
+
`changeEncryptionKey`. CLI: `okdb rekey --reencrypt --env <name> [--to <key> | --plain]`.
|
|
117
|
+
|
|
118
|
+
## Errors
|
|
119
|
+
|
|
120
|
+
| Code | Meaning |
|
|
121
|
+
| ------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
|
122
|
+
| `ENCRYPTION_KEY_INVALID` | the key given is not a key of this environment (its keyring is wrapped by another one) |
|
|
123
|
+
| `ENCRYPTION_KEY_REQUIRED` | the environment is encrypted but no key was given (or its function key was not passed again) |
|
|
124
|
+
| `ENV_ENCRYPTION_MISMATCH` | an LMDB file of an encrypted environment is not encrypted (or the reverse) |
|
|
125
|
+
| `FILE_NOT_ENCRYPTED` | a blob of an encrypted environment is not encrypted |
|
|
126
|
+
| `REKEY_IN_PROGRESS` / `REKEY_BUSY` / `REKEY_PEERS_BUSY` | retryable: a re-encryption (or compaction) is running |
|
|
127
|
+
|
|
128
|
+
## Upgrading from 3.0
|
|
129
|
+
|
|
130
|
+
A store encrypted by 3.0 keeps its key as each environment's data key: the 3.1.0 storage migration writes the keyrings and
|
|
131
|
+
re-encrypts the files 3.0 left plain; no encrypted data is rewritten. Rotate the data keys afterwards with `reencrypt` if you want
|
|
132
|
+
them random.
|
package/docs/files.md
CHANGED
|
@@ -8,29 +8,37 @@ OKDB includes content-addressable blob storage integrated with the database. Fil
|
|
|
8
8
|
|
|
9
9
|
## Uploading a file
|
|
10
10
|
|
|
11
|
-
`upload()` takes a readable stream and an id you choose:
|
|
11
|
+
`upload()` takes the bytes (a readable stream, a `Buffer`/`Uint8Array`, or a string) and an id you choose:
|
|
12
12
|
|
|
13
13
|
```javascript
|
|
14
|
-
const fs = require('fs');
|
|
15
|
-
const
|
|
14
|
+
const fs = require('node:fs');
|
|
15
|
+
const path = require('node:path');
|
|
16
|
+
|
|
17
|
+
const localFile = path.join(__dirname, 'alice.jpg');
|
|
18
|
+
fs.writeFileSync(localFile, Buffer.from([0xff, 0xd8, 0xff, 0xe0])); // stand-in image bytes
|
|
16
19
|
|
|
17
20
|
const record = await okdb.files.upload({
|
|
18
21
|
id: 'avatar-alice', // required — the ~files key
|
|
19
|
-
stream: fs.createReadStream(
|
|
22
|
+
stream: fs.createReadStream(localFile), // required — a stream, Buffer or string
|
|
20
23
|
mime: 'image/jpeg', // default 'application/octet-stream'
|
|
21
24
|
path: '/avatars/alice.jpg', // optional, full path incl. filename
|
|
22
25
|
});
|
|
23
26
|
// record = { id, hash, size, mime, path, createdAt }
|
|
24
27
|
|
|
25
28
|
// From a Buffer
|
|
26
|
-
await okdb.files.upload({ id: 'notes-1', stream:
|
|
29
|
+
await okdb.files.upload({ id: 'notes-1', stream: Buffer.from('hello'), mime: 'text/plain', path: '/notes/1.txt' });
|
|
27
30
|
```
|
|
28
31
|
|
|
29
|
-
The bytes are streamed to disk while hashed, then stored
|
|
32
|
+
The bytes are streamed to disk while hashed, then stored in the environment's blob store, `<env-path>/~blobs/<first2>/<rest>` (the SHA-256 hex; in an encrypted environment the file is encrypted and named by an HMAC of the hash, see [Storage layout](#storage-layout)). Uploading the same bytes again in the same environment stores them once — the new record points at the existing blob and its reference count goes up. Uploading again under an existing `id` replaces the file: the record is overwritten and the previous blob's reference is released (its file is deleted once nothing else references it). Re-uploading the same bytes under the same `id` leaves the reference count unchanged.
|
|
30
33
|
|
|
31
34
|
Pass `txn` to make the metadata write part of a transaction: the record is written with the transaction, the reference counts (including the release of a replaced blob) are updated after it commits, and a newly written blob is deleted if it rolls back — a rollback leaves the previous blob untouched.
|
|
32
35
|
|
|
36
|
+
<!-- continues -->
|
|
37
|
+
|
|
33
38
|
```javascript
|
|
39
|
+
await okdb.registerType('invoices');
|
|
40
|
+
const stream = fs.createReadStream(localFile); // any readable stream
|
|
41
|
+
|
|
34
42
|
const txn = okdb.transaction();
|
|
35
43
|
await okdb.files.upload({ id: 'invoice-7', stream, mime: 'application/pdf', path: '/invoices/7.pdf', txn });
|
|
36
44
|
txn.put('invoices', '7', { file: 'invoice-7', total: 120 });
|
|
@@ -41,6 +49,8 @@ await txn.commit();
|
|
|
41
49
|
|
|
42
50
|
## Reading a file
|
|
43
51
|
|
|
52
|
+
<!-- continues -->
|
|
53
|
+
|
|
44
54
|
```javascript
|
|
45
55
|
// Metadata (sync) — the ~files record or null
|
|
46
56
|
const meta = okdb.files.get('avatar-alice');
|
|
@@ -49,8 +59,8 @@ const meta = okdb.files.get('avatar-alice');
|
|
|
49
59
|
const buf = await okdb.files.read('avatar-alice');
|
|
50
60
|
|
|
51
61
|
// Stream it
|
|
52
|
-
const
|
|
53
|
-
stream.pipe(
|
|
62
|
+
const download = await okdb.files.stream('avatar-alice'); // → { stream, record }
|
|
63
|
+
download.stream.pipe(fs.createWriteStream(path.join(__dirname, 'copy.jpg'))); // e.g. pipe into an HTTP response
|
|
54
64
|
```
|
|
55
65
|
|
|
56
66
|
`read()` and `stream()` reject with `status: 404` when the id is unknown, or when the record exists but its blob is not on this node (`Blob missing for file: <id>`). `get()`, `read()` and `stream()` never create the `~files` type.
|
|
@@ -59,9 +69,14 @@ stream.pipe(response);
|
|
|
59
69
|
|
|
60
70
|
## Deleting a file
|
|
61
71
|
|
|
72
|
+
<!-- continues -->
|
|
73
|
+
|
|
62
74
|
```javascript
|
|
63
75
|
await okdb.files.remove('avatar-alice');
|
|
64
|
-
|
|
76
|
+
|
|
77
|
+
const tx = okdb.transaction();
|
|
78
|
+
await okdb.files.remove('invoice-7', { txn: tx }); // inside a transaction
|
|
79
|
+
await tx.commit();
|
|
65
80
|
```
|
|
66
81
|
|
|
67
82
|
`remove()` deletes the metadata record and decrements the blob's reference count; the blob file is deleted when no `~files` record references that hash any more. It rejects with `status: 404` when the id is unknown.
|
|
@@ -70,6 +85,8 @@ await okdb.files.remove('invoice-7', { txn }); // inside a transaction
|
|
|
70
85
|
|
|
71
86
|
## Listing files
|
|
72
87
|
|
|
88
|
+
<!-- continues -->
|
|
89
|
+
|
|
73
90
|
```javascript
|
|
74
91
|
// Everything (up to `limit`, default 1000)
|
|
75
92
|
const all = await okdb.files.listPath('/');
|
|
@@ -102,7 +119,7 @@ When the HTTP server is running, file routes are mounted for the default environ
|
|
|
102
119
|
| `GET` | `/api/files/:id/status` | Metadata plus `blob: { refs }` |
|
|
103
120
|
| `DELETE` | `/api/files/:id` | Remove → `204` |
|
|
104
121
|
|
|
105
|
-
Blob routes
|
|
122
|
+
Blob routes address one environment's blob store with `?env=<name>` (default: `default`):
|
|
106
123
|
|
|
107
124
|
| Method | Path | Description |
|
|
108
125
|
| ------ | ------------------------- | -------------------------------------------------------------------------------------- |
|
|
@@ -132,36 +149,39 @@ curl "http://localhost:8080/api/env/analytics/files?path=/exports/" -H "Authoriz
|
|
|
132
149
|
|
|
133
150
|
## Files per environment
|
|
134
151
|
|
|
135
|
-
Each OKDB environment has its own `~files` type
|
|
152
|
+
Each OKDB environment has its own `~files` type and its own blob store (`<env-path>/~blobs`). This means:
|
|
136
153
|
|
|
137
|
-
- The same bytes stored in `default` and in `analytics` are
|
|
138
|
-
- Reference counting tracks how many
|
|
139
|
-
-
|
|
154
|
+
- The same bytes stored twice in one environment are one file on disk; stored in `default` and in `analytics` they are two
|
|
155
|
+
- Reference counting tracks how many of the environment's records point to each hash; the blob is deleted when that drops to zero
|
|
156
|
+
- An environment's blobs are encrypted with that environment's key (its own `encryptionKey`, else the instance's), and `removeEnvironment()` deletes them with it
|
|
140
157
|
|
|
141
158
|
```javascript
|
|
159
|
+
await okdb.createEnvironment('analytics');
|
|
142
160
|
const analytics = okdb.env('analytics');
|
|
143
|
-
await analytics.files.upload({ id: 'q3', stream, mime: 'text/csv', path: '/exports/q3.csv' });
|
|
161
|
+
await analytics.files.upload({ id: 'q3', stream: 'region,total\nEU,120\n', mime: 'text/csv', path: '/exports/q3.csv' });
|
|
144
162
|
```
|
|
145
163
|
|
|
146
164
|
---
|
|
147
165
|
|
|
148
166
|
## Storage layout
|
|
149
167
|
|
|
150
|
-
```
|
|
151
|
-
<
|
|
152
|
-
ab/cdef1234... ← blob file (path = first2/rest of SHA-256 hex)
|
|
168
|
+
```text
|
|
169
|
+
<env-path>/~blobs/
|
|
170
|
+
ab/cdef1234... ← blob file (path = first2/rest of the SHA-256 hex; with a key: of HMAC-SHA256(file key, hash), contents encrypted)
|
|
153
171
|
ff/0123abcd...
|
|
154
172
|
tmp/ ← in-flight uploads
|
|
155
173
|
```
|
|
156
174
|
|
|
157
|
-
|
|
175
|
+
Records and the API always carry the real SHA-256. Before 3.1 all environments shared `<okdb-root>/~blobs`; the 3.1.0 storage migration moves each blob into every environment that references it.
|
|
158
176
|
|
|
159
|
-
|
|
177
|
+
In the database:
|
|
178
|
+
|
|
179
|
+
```text
|
|
160
180
|
~files ← metadata records, per env (id → { id, hash, size, mime, path, createdAt })
|
|
161
|
-
~file:blob_status ← ref-counting sub-db
|
|
181
|
+
~file:blob_status ← ref-counting sub-db, per env (hash → { refs, nodes })
|
|
162
182
|
```
|
|
163
183
|
|
|
164
|
-
Maintenance helpers: `files.getBlobStatus(hash)` → `{ refs,
|
|
184
|
+
Maintenance helpers: `files.getBlobStatus(hash)` → `{ refs, … } | null`, `files.listBlobStatus()` (the blob table), `files.gcOrphanedBlobs({ minAgeMs })` (deletes blob files whose ref count is 0 or unknown and that no `~files` record references, skipping blobs modified in the last `minAgeMs` — default 10 minutes — since an upload in flight writes its blob before its record; returns the count).
|
|
165
185
|
|
|
166
186
|
---
|
|
167
187
|
|
|
@@ -181,18 +201,33 @@ So metadata can arrive before the bytes. Until they do, `read()`/`stream()` on t
|
|
|
181
201
|
Full-text search and embeddings can index what is **in** the files, not only their paths. Turn it on once per environment:
|
|
182
202
|
|
|
183
203
|
```javascript
|
|
204
|
+
await okdb.files.upload({
|
|
205
|
+
id: 'report',
|
|
206
|
+
stream: 'Quarterly revenue grew 12%.',
|
|
207
|
+
mime: 'text/plain',
|
|
208
|
+
path: '/docs/report.txt',
|
|
209
|
+
});
|
|
210
|
+
|
|
184
211
|
await okdb.files.indexContent(); // or env.files.indexContent({ field, maxBytes })
|
|
185
212
|
```
|
|
186
213
|
|
|
187
214
|
This declares `content` on `~files` as a [resolved field](./resolved-fields.md): nothing is copied into the database — when an index needs a file's content, okdb reads the blob and runs a matching **extractor** to turn the bytes into text. Then index `~files` like any type:
|
|
188
215
|
|
|
216
|
+
<!-- continues -->
|
|
217
|
+
|
|
189
218
|
```javascript
|
|
190
219
|
// Full-text search over path + content
|
|
191
220
|
await okdb.fts.ensure('~files', 'text', { fields: ['path', 'content'] });
|
|
221
|
+
await okdb.fts.flush('~files');
|
|
192
222
|
const hits = okdb.ftsQuery('~files', 'text', 'quarterly revenue');
|
|
193
|
-
for (const { key, value } of hits) console.log(key, value.path);
|
|
223
|
+
for (const { key, value } of hits) console.log(key, value.path); // report /docs/report.txt
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Semantic search over the same content:
|
|
194
227
|
|
|
195
|
-
|
|
228
|
+
<!-- not-runnable: needs an ML model -->
|
|
229
|
+
|
|
230
|
+
```javascript
|
|
196
231
|
const pipeline = await okdb.embeddings.createPipeline('file-search', {
|
|
197
232
|
source_type: '~files',
|
|
198
233
|
field: 'content',
|
|
@@ -219,8 +254,9 @@ The setting is durable: every process that opens the store — a restart, a seco
|
|
|
219
254
|
Built in: `text/*`, `application/json`, `application/xml`, `application/javascript`, `*+json` and `*+xml` are decoded as UTF-8. Nothing else is built in — okdb ships no PDF/Office parsers. For other formats, register an extractor:
|
|
220
255
|
|
|
221
256
|
```javascript
|
|
222
|
-
// Your choice of parser — okdb has no dependency on it.
|
|
223
|
-
const pdfToText =
|
|
257
|
+
// Your choice of parser — okdb has no dependency on it. Stand-ins for this example:
|
|
258
|
+
const pdfToText = async (buffer) => buffer.toString('latin1');
|
|
259
|
+
const docxToText = async (buffer) => null;
|
|
224
260
|
|
|
225
261
|
okdb.files.registerExtractor('application/pdf', async (buffer, record) => {
|
|
226
262
|
return await pdfToText(buffer); // string, or null for "no content"
|
|
@@ -228,10 +264,11 @@ okdb.files.registerExtractor('application/pdf', async (buffer, record) => {
|
|
|
228
264
|
|
|
229
265
|
// A wildcard or a predicate on the record also works
|
|
230
266
|
okdb.files.registerExtractor('application/vnd.openxmlformats-officedocument.*', docxToText);
|
|
231
|
-
okdb.files.registerExtractor(
|
|
267
|
+
const unregister = okdb.files.registerExtractor(
|
|
232
268
|
(record) => record.path.endsWith('.log'),
|
|
233
269
|
(buf) => buf.toString('latin1'),
|
|
234
270
|
);
|
|
271
|
+
unregister(); // registerExtractor returns an unregister function
|
|
235
272
|
```
|
|
236
273
|
|
|
237
274
|
- `match` is a mime (`'application/pdf'`), a wildcard (`'text/*'`, `'*+json'`), or a predicate `(record) => boolean`. Mime parameters are ignored (`text/plain; charset=utf-8` matches `text/plain`).
|
package/docs/fts.md
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
# Full-Text Search
|
|
2
2
|
|
|
3
|
-
OKDB includes a built-in full-text search engine. All FTS data for an environment lives in two shared
|
|
3
|
+
OKDB includes a built-in full-text search engine. All FTS data for an environment lives in two shared stores under `~fts/` — one inverted/uncompressed (posting lists + dictionaries), one compressed (forward index). Indexes are differentiated by an auto-increment `ftsId` used as a key prefix inside the shared stores, so adding indexes adds no new files and no per-index overhead. FTS is part of the free tier.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
## Registering an FTS index
|
|
8
8
|
|
|
9
9
|
```javascript
|
|
10
|
+
await okdb.registerType('articles');
|
|
11
|
+
await okdb.put('articles', 'a0', {
|
|
12
|
+
title: 'Embedded database for Node.js',
|
|
13
|
+
body: 'Fast and local.',
|
|
14
|
+
status: 'published',
|
|
15
|
+
});
|
|
16
|
+
|
|
10
17
|
await okdb.fts.register('articles', 'content', {
|
|
11
18
|
fields: ['title', 'body'], // fields to index
|
|
12
19
|
tokenizer: {
|
|
@@ -14,21 +21,29 @@ await okdb.fts.register('articles', 'content', {
|
|
|
14
21
|
maxTokenLength: 64,
|
|
15
22
|
keepNumbers: true,
|
|
16
23
|
toLower: true, // case-insensitive search
|
|
24
|
+
stopwords: ['the', 'a'], // optional — tokens never indexed
|
|
17
25
|
},
|
|
18
26
|
});
|
|
19
27
|
```
|
|
20
28
|
|
|
21
|
-
The index builds from existing data
|
|
29
|
+
The index builds from existing data on registration. Wait for it:
|
|
30
|
+
|
|
31
|
+
<!-- continues -->
|
|
22
32
|
|
|
23
33
|
```javascript
|
|
24
34
|
await okdb.fts.ready('articles');
|
|
25
35
|
```
|
|
26
36
|
|
|
37
|
+
`okdb.fts.ensure(type, name, config)` is the idempotent form: it registers the index if it does not exist and otherwise leaves it as is.
|
|
38
|
+
|
|
27
39
|
### Multiple FTS indexes on one type
|
|
28
40
|
|
|
29
41
|
You can have several FTS indexes on the same type, each covering different fields or using different tokenizer settings. All of them share the env-level storage — adding a second index does not double your disk usage.
|
|
30
42
|
|
|
43
|
+
<!-- continues -->
|
|
44
|
+
|
|
31
45
|
```javascript
|
|
46
|
+
await okdb.registerType('products');
|
|
32
47
|
await okdb.fts.register('products', 'name', { fields: ['name'] });
|
|
33
48
|
await okdb.fts.register('products', 'description', {
|
|
34
49
|
fields: ['description'],
|
|
@@ -40,6 +55,8 @@ await okdb.fts.register('products', 'description', {
|
|
|
40
55
|
|
|
41
56
|
## Querying
|
|
42
57
|
|
|
58
|
+
<!-- continues -->
|
|
59
|
+
|
|
43
60
|
```javascript
|
|
44
61
|
const results = okdb.ftsQuery('articles', 'content', 'embedded database Node.js');
|
|
45
62
|
for (const { key, value } of results) {
|
|
@@ -47,13 +64,13 @@ for (const { key, value } of results) {
|
|
|
47
64
|
}
|
|
48
65
|
```
|
|
49
66
|
|
|
50
|
-
`ftsQuery` returns records that contain all of the query tokens by default (AND), as `{ key, value, version, score, numTerms, maxScore }` ordered by relevance, **at most 50 by default** (`options.limit`). Use `options.mode: 'or'` for OR semantics, and `options.prefix: true` for prefix matching. `okdb.fts.search(type, name, text, options?)` is the keys-only form (a `string[]`, same default limit).
|
|
67
|
+
`ftsQuery` returns records that contain all of the query tokens by default (AND), as `{ key, value, version, score, numTerms, maxScore }` ordered by relevance, **at most 50 by default** (`options.limit`). Use `options.mode: 'or'` for OR semantics, and `options.prefix: true` for prefix matching. `okdb.fts.search(type, name, text, options?)` is the keys-only form (a `string[]`, same default limit). Both work on any env: `env.ftsQuery(...)`, or pass the env (object or name) as the last argument of `okdb.fts.search(type, name, text, options, env)`.
|
|
51
68
|
|
|
52
69
|
### Relevance scoring (BM25)
|
|
53
70
|
|
|
54
71
|
Results are ranked with [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) (k1 = 1.2, b = 0.75):
|
|
55
72
|
|
|
56
|
-
```
|
|
73
|
+
```text
|
|
57
74
|
score(doc) = Σ over query tokens idf · tf·(k1+1) / (tf + k1·(1 − b + b·docLength/avgDocLength))
|
|
58
75
|
idf = ln(1 + (N − df + 0.5) / (df + 0.5))
|
|
59
76
|
```
|
|
@@ -80,8 +97,10 @@ Pass a sift-compatible filter as the fourth argument to narrow results. The filt
|
|
|
80
97
|
pass (or the matches run out), so a selective filter still fills the page — no need to inflate
|
|
81
98
|
`limit`:
|
|
82
99
|
|
|
100
|
+
<!-- continues -->
|
|
101
|
+
|
|
83
102
|
```javascript
|
|
84
|
-
const
|
|
103
|
+
const published = okdb.ftsQuery('articles', 'content', 'database performance', {
|
|
85
104
|
status: 'published',
|
|
86
105
|
});
|
|
87
106
|
```
|
|
@@ -92,8 +111,10 @@ filter and index constraint the same way (see [Hybrid queries](./querying.md#hyb
|
|
|
92
111
|
|
|
93
112
|
### Options
|
|
94
113
|
|
|
114
|
+
<!-- continues -->
|
|
115
|
+
|
|
95
116
|
```javascript
|
|
96
|
-
const
|
|
117
|
+
const firstPage = okdb.ftsQuery('articles', 'content', 'hello world', null, {
|
|
97
118
|
limit: 20,
|
|
98
119
|
mode: 'and', // 'and' (default) | 'or' — OR ranks docs matching more/rarer tokens first
|
|
99
120
|
prefix: false, // enable prefix matching on tokens
|
|
@@ -104,6 +125,8 @@ const results = okdb.ftsQuery('articles', 'content', 'hello world', null, {
|
|
|
104
125
|
|
|
105
126
|
## Index management
|
|
106
127
|
|
|
128
|
+
<!-- continues -->
|
|
129
|
+
|
|
107
130
|
```javascript
|
|
108
131
|
// Check if an index exists
|
|
109
132
|
okdb.fts.has('articles', 'content'); // → boolean
|
|
@@ -123,11 +146,11 @@ okdb.fts.list('articles');
|
|
|
123
146
|
// Env-level storage summary across all FTS indexes
|
|
124
147
|
okdb.fts.envSize();
|
|
125
148
|
// → {
|
|
126
|
-
// diskBytes, // ~fts/<env>/ + ~fts/<env>_docs/
|
|
149
|
+
// diskBytes, // ~fts/<env>/ + ~fts/<env>_docs/ file sizes
|
|
127
150
|
// payloadBytes, // actual stored bytes (indexes + shared dicts)
|
|
128
151
|
// indexPayloadBytes, // payload attributable to indexes only
|
|
129
152
|
// sharedDictBytes, // shared docKey↔docId and token↔tokenId mappings
|
|
130
|
-
// slackBytes, //
|
|
153
|
+
// slackBytes, // free pages (reclaimable via env.compact)
|
|
131
154
|
// indexes: [{ type, name, sizeBytes }],
|
|
132
155
|
// }
|
|
133
156
|
|
|
@@ -142,9 +165,9 @@ await okdb.fts.drop('articles', 'content');
|
|
|
142
165
|
|
|
143
166
|
## Storage architecture
|
|
144
167
|
|
|
145
|
-
OKDB's FTS uses a two-tier inverted index with Roaring bitmaps and ID interning. The names below are the actual
|
|
168
|
+
OKDB's FTS uses a two-tier inverted index with Roaring bitmaps and ID interning. The names below are the actual sub-database names in `~fts/<envName>/data.mdb`:
|
|
146
169
|
|
|
147
|
-
```
|
|
170
|
+
```text
|
|
148
171
|
~fts/<envName>/data.mdb (uncompressed env)
|
|
149
172
|
post dupSort [ftsId, token] → docId (live "add" tier)
|
|
150
173
|
postDel dupSort [ftsId, token] → docId (live "delete" tombstones)
|
|
@@ -180,16 +203,14 @@ length plus the corpus size `N` and average length.
|
|
|
180
203
|
|
|
181
204
|
**Reads** merge all three tiers: `frozen ∪ liveAdds − liveDeletes`. Roaring's set operations make this essentially free.
|
|
182
205
|
|
|
183
|
-
**Writes** only touch the live tier — never the frozen tier. The hot path is one dupSort
|
|
206
|
+
**Writes** only touch the live tier — never the frozen tier. The hot path is one dupSort put per added token.
|
|
184
207
|
|
|
185
208
|
### Compaction
|
|
186
209
|
|
|
187
210
|
The compactor periodically rolls live entries into the frozen tier. It runs in two situations:
|
|
188
211
|
|
|
189
212
|
1. **Automatically after `fts.flush(type)`** — keeps the live tier small after a known burst of writes.
|
|
190
|
-
2. **Explicitly via `fts.compactStorage(env)` or `env.compact()`** — also reclaims `data.mdb` slack by rewriting the file (
|
|
191
|
-
|
|
192
|
-
After a stress run of 13k docs across 5 indexes, `env.compact()` typically reclaims ~75% of the FTS file size in a few seconds, with no impact on search.
|
|
213
|
+
2. **Explicitly via `fts.compactStorage(env)` or `env.compact()`** — also reclaims `data.mdb` slack by rewriting the file (the storage never shrinks files in place; freed pages are reused but the high-water mark stays). Search keeps answering throughout.
|
|
193
214
|
|
|
194
215
|
### Storage format versioning
|
|
195
216
|
|
|
@@ -205,16 +226,19 @@ open, still without clearing. Only participating (`processors: true`) instances
|
|
|
205
226
|
|
|
206
227
|
## Async indexing
|
|
207
228
|
|
|
208
|
-
FTS writes are **always async** — the FTS index is updated by a background processor after each write commits. Secondary indexes (field indexes, geo indexes) update synchronously inside the same
|
|
229
|
+
FTS writes are **always async** — the FTS index is updated by a background processor after each write commits. Secondary indexes (field indexes, geo indexes) update synchronously inside the same transaction as the write, so they are immediately consistent. FTS isn't.
|
|
209
230
|
|
|
210
231
|
```javascript
|
|
232
|
+
await okdb.registerType('articles');
|
|
233
|
+
await okdb.fts.register('articles', 'main', { fields: ['title'] });
|
|
234
|
+
|
|
211
235
|
await okdb.put('articles', 'a1', { title: 'Hello world' });
|
|
212
|
-
//
|
|
236
|
+
// a1 is in the primary data; the FTS index may not have it yet.
|
|
213
237
|
|
|
214
238
|
await okdb.fts.flush('articles');
|
|
215
|
-
// Now it
|
|
239
|
+
// Now it does — and the live tier has been compacted into the frozen tier.
|
|
216
240
|
|
|
217
|
-
const results = okdb.fts.search('articles', 'main', 'hello'); //
|
|
241
|
+
const results = okdb.fts.search('articles', 'main', 'hello'); // → ['a1']
|
|
218
242
|
```
|
|
219
243
|
|
|
220
244
|
### `ready(type)`
|
|
@@ -240,10 +264,11 @@ Default behaviour:
|
|
|
240
264
|
|
|
241
265
|
- Splits on whitespace and punctuation
|
|
242
266
|
- Lowercases (when `toLower: true`, default)
|
|
243
|
-
- Discards tokens shorter than `minTokenLength` (default 2)
|
|
244
|
-
- Keeps
|
|
267
|
+
- Discards tokens shorter than `minTokenLength` (default 2) and cuts tokens longer than `maxTokenLength` (default 64) to that length
|
|
268
|
+
- Keeps pure-number tokens by default (`keepNumbers: true`)
|
|
269
|
+
- Drops the tokens listed in `stopwords` (default: none)
|
|
245
270
|
|
|
246
|
-
You can override per
|
|
271
|
+
There is no stemming and no language-specific rule. You can override these per index in the `register()` config.
|
|
247
272
|
|
|
248
273
|
---
|
|
249
274
|
|
|
@@ -256,7 +281,7 @@ FTS environments are not replicated. On a new node they rebuild from synced type
|
|
|
256
281
|
## Example: articles with FTS
|
|
257
282
|
|
|
258
283
|
```javascript
|
|
259
|
-
await okdb.
|
|
284
|
+
await okdb.registerType('articles');
|
|
260
285
|
await okdb.fts.register('articles', 'search', {
|
|
261
286
|
fields: ['title', 'body', 'tags'],
|
|
262
287
|
});
|
|
@@ -264,7 +289,7 @@ await okdb.fts.ready('articles');
|
|
|
264
289
|
|
|
265
290
|
await okdb.put('articles', 'a1', {
|
|
266
291
|
title: 'Getting started with LMDB',
|
|
267
|
-
body: 'LMDB is a B+ tree key-value store with MVCC
|
|
292
|
+
body: 'LMDB is a B+ tree key-value store with MVCC.',
|
|
268
293
|
tags: ['database', 'lmdb', 'storage'],
|
|
269
294
|
});
|
|
270
295
|
|