@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
package/docs/processors.md
CHANGED
|
@@ -20,7 +20,7 @@ OKDB's own features (indexes, views, FTS, materializer, embeddings, time-machine
|
|
|
20
20
|
|
|
21
21
|
## Modes — the delivery guarantee
|
|
22
22
|
|
|
23
|
-
A mode names the **delivery guarantee**: how many instances run the handler. All drains run
|
|
23
|
+
A mode names the **delivery guarantee**: how many instances run the handler. All drains run in the owner process, chunked into cooperative quanta (`OKDB_PROCESSOR_FLUSH_QUANTUM`-bounded batches, default 5 000, with a yield between them) so a large drain never blocks the process monolithically; your JS handler runs on the Node event loop. There is no execution placement to configure — no thread pool, no `runIn`. Handlers register per process: pass `handler:'<name>'` (named registry), `module:{path,export}`, or — for internal features — a closure paired with a reconstructible `quantum` (see [Registering a processor](#registering-a-processor)).
|
|
24
24
|
|
|
25
25
|
The public vocabulary is two options: **`mode ∈ {'sync', 'async'}`** (timing) and, for `async` only, **`distribution ∈ {'single', 'fanout'}`**. They resolve to one of three internal tokens, which is what `status().mode` reports:
|
|
26
26
|
|
|
@@ -45,44 +45,47 @@ Omitting `mode` is `{mode:'async', distribution:'single'}`. `distribution` witho
|
|
|
45
45
|
## Registering a processor
|
|
46
46
|
|
|
47
47
|
```javascript
|
|
48
|
-
// ./order-stats.js
|
|
49
|
-
|
|
48
|
+
// the handler — normally its own file, e.g. ./order-stats.js: `exports.apply = async (ctx, changes, info) => { ... }`
|
|
49
|
+
const apply = async (ctx, changes, info) => {
|
|
50
50
|
// ctx = { env, payload } info = { mode, type, fromClock, toClock }
|
|
51
51
|
for (const c of changes) {
|
|
52
52
|
// c.type, c.key, c.action ('put' | 'remove' | schema actions such as 'registerType'), c.clock, c.value?
|
|
53
53
|
}
|
|
54
54
|
};
|
|
55
|
+
env.processor.constructor.registerHandler('order-stats', apply);
|
|
55
56
|
|
|
56
|
-
|
|
57
|
+
await env.registerType('Order');
|
|
57
58
|
const stop = env.processor.register('Order', {
|
|
58
59
|
mode: 'async', // default; distribution defaults to 'single'
|
|
59
60
|
name: 'order-stats', // shown in admin / status
|
|
60
61
|
cursorKey: 'order-stats', // durable resume key — unique per processor
|
|
61
62
|
originMode: 'all', // 'self' (default) | 'remote' | 'all'
|
|
62
|
-
module: { path: require.resolve('./order-stats.js'), export: 'apply' }
|
|
63
|
+
handler: 'order-stats', // or: module: { path: require.resolve('./order-stats.js'), export: 'apply' }
|
|
63
64
|
payload: { bucket: 'daily' }, // optional — handed to the handler as ctx.payload
|
|
64
65
|
});
|
|
65
66
|
|
|
67
|
+
await env.put('Order', 'o1', { total: 10 });
|
|
68
|
+
|
|
66
69
|
// Control surface:
|
|
67
|
-
|
|
70
|
+
stop.kick(); // schedule a drain now
|
|
71
|
+
await stop.awaitIdle();
|
|
68
72
|
stop.status(); // live status { state, lastClock, lag, mode, ... }
|
|
69
73
|
stop.pause();
|
|
70
74
|
stop.resume();
|
|
71
75
|
stop.retry();
|
|
72
|
-
stop
|
|
73
|
-
await stop.awaitIdle();
|
|
76
|
+
await stop(); // unregister + release the lease
|
|
74
77
|
```
|
|
75
78
|
|
|
76
79
|
The handler must be **reconstructible by any process**, so it is named, not passed as a bare closure. Exactly one of:
|
|
77
80
|
|
|
78
81
|
- `module: { path, export }` — a file `require()`d by the registering process (`export` defaults to `'process'`, then the module's default export).
|
|
79
|
-
- `handler: '<name>'` — a function registered in-process with `
|
|
82
|
+
- `handler: '<name>'` — a function registered in-process with `env.processor.constructor.registerHandler(name, fn)` (the processor class is not exported from the package root).
|
|
80
83
|
|
|
81
84
|
Both are called as `fn(ctx, changes, info)`. A bare closure (`handler: async (changes) => …`) **throws** `processor: closure handlers are not accepted`. Closures are only accepted on internal paths — paired with a `quantum` (FTS, time machine, materializer) or with `definition: { durable: true }` (inline index/view processors) — and are called with the legacy `(changes, info)` signature.
|
|
82
85
|
|
|
83
86
|
`changes` are change-log records (`{ type, key, action, clock, origin, ... }`). With the default `hydrateValues: true`, `put` records also carry `.value` (the current document); otherwise read the document via `ctx.env.get(c.type, c.key)`.
|
|
84
87
|
|
|
85
|
-
`originMode` filters by who wrote the change (compared to the change's `origin`, the writing store's identity — shared by every process on the same path): `self` (default — this store's writes, including a cloned store's history from before the copy), `remote` (writes synced in from other stores), or `all`. It applies on every delivery path — inline, async live drains, log replay and the snapshot bootstrap (which judges each doc by its latest change). A drain chunk whose changes are all filtered out is not delivered, and the cursor still moves past it. A `quantum` module receives the mode as `payload.originMode` and applies it itself
|
|
88
|
+
`originMode` filters by who wrote the change (compared to the change's `origin`, the writing store's identity — shared by every process on the same path): `self` (default — this store's writes, including a cloned store's history from before the copy), `remote` (writes synced in from other stores), or `all`. It applies on every delivery path — inline, async live drains, log replay and the snapshot bootstrap (which judges each doc by its latest change). A drain chunk whose changes are all filtered out is not delivered, and the cursor still moves past it. A `quantum` module receives the mode as `payload.originMode` and applies it itself, as the built-in quanta do. Async processors with `remote`/`all` also wake on cross-process writes via the bus.
|
|
86
89
|
|
|
87
90
|
**`rebuild` (snapshot-bootstrap processors).** With `bootstrap: 'snapshot'` you may pass `rebuild: async () => { ... }` — a feature-owned **full rebuild** (scan the actual docs, then reposition the cursor via `setCursor` + `markSnapshotComplete`). It runs whenever the processor bootstraps with an **un-positioned cursor**: after a cursor reset (the admin ⟲ "full reprocess"), or when a build handoff was interrupted by a crash. Without it, the framework's only option is replaying the changelog from 0 — which is **not** a rebuild: sync-GC prunes the changelog (its horizon ignores processor cursors), so replay-from-0 can silently yield a partial derived store. FTS registers one (re-scans all docs of the type into every index, clearing first).
|
|
88
91
|
|
|
@@ -90,7 +93,7 @@ Both are called as `fn(ctx, changes, info)`. A bare closure (`handler: async (ch
|
|
|
90
93
|
|
|
91
94
|
## Snapshot bootstrap and chunked drains
|
|
92
95
|
|
|
93
|
-
A `single` processor with `bootstrap: 'snapshot'` performs a cooperative snapshot scan, yielding every batch so the event loop stays responsive while a large type is bootstrapped. Live drains
|
|
96
|
+
A `single` processor with `bootstrap: 'snapshot'` performs a cooperative snapshot scan, yielding every batch so the event loop stays responsive while a large type is bootstrapped. Live drains are chunked (`OKDB_PROCESSOR_FLUSH_QUANTUM` bounds each quantum, then yields; heavy per-item features pass a smaller per-processor `flushQuantum`). A feature may supply a reconstructible **`quantum`** module — it re-derives the work for a clock range and commits it durably (optionally advancing the cursor atomically with its output, `selfCursor`) before the cursor moves. This is exactly the path FTS uses — every FTS-indexed type registers a `single`-mode processor (hydrate + tokenize + posting writes) drained in small bounded quanta.
|
|
94
97
|
|
|
95
98
|
The cursor only advances on a successful drain, so processing is **at-least-once**; make handlers idempotent. Derived state is eventually-consistent; if you need a deterministic "caught up" point, wait on `stop.status().lastClock` reaching the source clock.
|
|
96
99
|
|
|
@@ -98,36 +101,36 @@ The cursor only advances on a successful drain, so processing is **at-least-once
|
|
|
98
101
|
|
|
99
102
|
## Cross-process behaviour
|
|
100
103
|
|
|
101
|
-
Each processor takes a lease (the `'proc'` lock). With several processes open on the same env, exactly one runs each `single` processor; the others wait and take over if the holder dies. The lease-holding process
|
|
104
|
+
Each processor takes a lease (the `'proc'` lock). With several processes open on the same env, exactly one runs each `single` processor; the others wait and take over if the holder dies. The lease-holding process does the drain, so there is always a single writer to your derived store.
|
|
102
105
|
|
|
103
106
|
Under sustained load the lease **load-shares by cooperative hold-window claiming**: the holder drains for up to `OKDB_LEASE_HOLD_MS` (200 ms) per window, and at the window boundary yields the lease **only if a peer has signalled it wants a turn** (`~lock:want`, a decaying marker written by waiting peers with backlog). A lone process therefore keeps its leases with zero lock churn; two loaded processes rotate and split the work ≈evenly. Waiting peers re-contend on a short cadence (~one hold window) while they have backlog and on the slow `ttl/2` failover cadence when idle.
|
|
104
107
|
|
|
105
108
|
A processor that hits an error **keeps its lease** (in-place `retry()`/`restart()` keeps its slot against standbys in other processes). Re-bootstrap reuses the held lease handle, and `tryAcquire` treats a fresh lease held by the same pid + processorId as a re-acquire — so an errored processor can never deadlock in `waiting` against its own heartbeat.
|
|
106
109
|
|
|
107
|
-
Cross-process wakes ride the
|
|
110
|
+
Cross-process wakes ride the bus (`SYSTEM_POKE`), which is lossy by design. An online holder therefore also runs an **idle catch-up tick** (`OKDB_PROCESSOR_CATCHUP_MS`, default 15 000, `0` disables): every interval it compares each single-mode registration's type head against its cursor and schedules a drain when behind, so a lost poke bounds staleness at one tick instead of "until the next write". The changelog GC in turn **never prunes past the slowest durable processor cursor** — a lagging drain finds its entries intact rather than silently skipping writes.
|
|
108
111
|
|
|
109
112
|
---
|
|
110
113
|
|
|
111
114
|
## Cookbook
|
|
112
115
|
|
|
113
|
-
- **A background derived indexer (like FTS)** — `mode: 'async'` (distribution `single`), module or named handler, drained
|
|
116
|
+
- **A background derived indexer (like FTS)** — `mode: 'async'` (distribution `single`), module or named handler, drained in chunked quanta.
|
|
114
117
|
- **An immediate-consistency derived field** — `mode: 'sync'` (cheap work only; it runs on the write path).
|
|
115
|
-
- **A per-process cache / light aggregate
|
|
118
|
+
- **A per-process cache / light aggregate in each process** — `mode: 'async', distribution: 'fanout'`.
|
|
116
119
|
|
|
117
120
|
---
|
|
118
121
|
|
|
119
|
-
## Runtime mode switching
|
|
122
|
+
## Runtime mode switching
|
|
120
123
|
|
|
121
124
|
`env.processor.setMode(logicalKey, mode, distribution?)` (HTTP: `POST /api/processors/:logicalKey/mode`)
|
|
122
125
|
switches a processor's mode at runtime through a durable config record (registry
|
|
123
126
|
desired-state scope `'procmode'`) + a clock-boundary handoff:
|
|
124
127
|
|
|
125
|
-
| transition | mechanics
|
|
126
|
-
| ----------------- |
|
|
127
|
-
| `single → fanout` | holder drains to clock C, releases the lease; every instance seeds its in-memory cursor at C
|
|
128
|
-
| `fanout → single` | instances stop at the flip; durable cursor seeded at max(C, head-at-observance); lease claiming begins
|
|
129
|
-
| `* → inline` |
|
|
130
|
-
| `inline → *` | inline stops on observance; the deferred cursor starts at the observance clock
|
|
128
|
+
| transition | mechanics |
|
|
129
|
+
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
130
|
+
| `single → fanout` | holder drains to clock C, releases the lease; every instance seeds its in-memory cursor at C |
|
|
131
|
+
| `fanout → single` | instances stop at the flip; durable cursor seeded at max(C, head-at-observance); lease claiming begins |
|
|
132
|
+
| `* → inline` | durable-definition gate re-checked (closures without a durable definition → rejected); gap-fill to head; a per-write version gate makes every writer observe the flip before its next commit |
|
|
133
|
+
| `inline → *` | inline stops on observance; the deferred cursor starts at the observance clock |
|
|
131
134
|
|
|
132
135
|
Transitions are serialized per processor (a flip while one is unapplied → `PROC_MODE_FLIP_IN_FLIGHT`).
|
|
133
136
|
Overlap windows double-run the deferred mode — the (already required) idempotency contract makes
|
|
@@ -154,7 +157,7 @@ there is no population to configure and no per-node dedication.
|
|
|
154
157
|
> construction) and `db.processors.process(filter)` / `processRest()` / `processEverything()`
|
|
155
158
|
> (throw with a migration message), plus per-node dedication/intent. Also removed: the
|
|
156
159
|
> `processing:` option family (`'auto'|'main'|'none'`, `'threads'|'processes'`) — there is no
|
|
157
|
-
> execution placement; every drain runs
|
|
160
|
+
> execution placement; every drain runs in its claimant process in bounded quanta.
|
|
158
161
|
> `asyncProcessors: true/false` is now `processors: true/false`. To dedicate hardware to
|
|
159
162
|
> processing, run that node `processors:true` and the others `processors:false`. See
|
|
160
163
|
> [Upgrading to 2.0](upgrade-2.0.md).
|
package/docs/querying.md
CHANGED
|
@@ -7,13 +7,34 @@ OKDB provides a layered query model: fast synchronous reads by key, ordered rang
|
|
|
7
7
|
## Single record reads
|
|
8
8
|
|
|
9
9
|
```javascript
|
|
10
|
+
// Setup used by the examples on this page
|
|
11
|
+
await okdb.registerType('users');
|
|
12
|
+
await okdb.registerIndex('users', ['role']);
|
|
13
|
+
await okdb.registerIndex('users', ['role', 'createdAt']);
|
|
14
|
+
await okdb.put('users', 'alice', {
|
|
15
|
+
name: 'Alice',
|
|
16
|
+
role: 'admin',
|
|
17
|
+
age: 41,
|
|
18
|
+
active: true,
|
|
19
|
+
createdAt: Date.now(),
|
|
20
|
+
profile: { verified: true },
|
|
21
|
+
});
|
|
22
|
+
await okdb.put('users', 'bob', {
|
|
23
|
+
name: 'Bob',
|
|
24
|
+
role: 'member',
|
|
25
|
+
age: 67,
|
|
26
|
+
active: true,
|
|
27
|
+
createdAt: Date.now(),
|
|
28
|
+
profile: { verified: false },
|
|
29
|
+
});
|
|
30
|
+
|
|
10
31
|
// Returns value or undefined
|
|
11
32
|
const user = okdb.get('users', 'alice');
|
|
12
33
|
|
|
13
34
|
// Returns { value, version } or undefined
|
|
14
35
|
const entry = okdb.getEntry('users', 'alice');
|
|
15
36
|
|
|
16
|
-
// Multiple keys at once — returns an array in the same order (
|
|
37
|
+
// Multiple keys at once — returns an array in the same order (undefined for missing)
|
|
17
38
|
const [alice, bob] = okdb.getMany('users', ['alice', 'bob']);
|
|
18
39
|
```
|
|
19
40
|
|
|
@@ -23,7 +44,9 @@ All reads are **synchronous**. LMDB maps the database file directly into process
|
|
|
23
44
|
|
|
24
45
|
## Range scans
|
|
25
46
|
|
|
26
|
-
Range scans return **lazy LMDB
|
|
47
|
+
Range scans return **lazy iterables** that read rows from LMDB in chunks as you iterate. `getRange` produces `{ key, value }` entries.
|
|
48
|
+
|
|
49
|
+
<!-- continues -->
|
|
27
50
|
|
|
28
51
|
```javascript
|
|
29
52
|
// All records in default order (key-lexicographic)
|
|
@@ -33,38 +56,52 @@ for (const { key, value } of okdb.getRange('users')) {
|
|
|
33
56
|
|
|
34
57
|
// Bounded range
|
|
35
58
|
for (const { key, value } of okdb.getRange('users', {
|
|
36
|
-
start: 'a',
|
|
37
|
-
end:
|
|
59
|
+
start: 'a', // inclusive lower bound
|
|
60
|
+
end: 'b', // EXCLUSIVE upper bound — 'b' itself is not returned
|
|
38
61
|
limit: 100,
|
|
39
62
|
reverse: false,
|
|
40
|
-
})) {
|
|
63
|
+
})) {
|
|
64
|
+
console.log(key, value.name);
|
|
65
|
+
}
|
|
41
66
|
```
|
|
42
67
|
|
|
43
68
|
Convenience iterables for when you only need one dimension:
|
|
44
69
|
|
|
70
|
+
<!-- continues -->
|
|
71
|
+
|
|
45
72
|
```javascript
|
|
46
73
|
// Keys only
|
|
47
|
-
for (const key of okdb.getKeys('users'))
|
|
74
|
+
for (const key of okdb.getKeys('users')) console.log(key);
|
|
48
75
|
|
|
49
76
|
// Values only
|
|
50
|
-
for (const value of okdb.getValues('users'))
|
|
77
|
+
for (const value of okdb.getValues('users')) console.log(value.name);
|
|
51
78
|
|
|
52
79
|
// Lexicographic prefix
|
|
53
|
-
for (const { key, value } of okdb.getByPrefix('users', 'team:'))
|
|
80
|
+
for (const { key, value } of okdb.getByPrefix('users', 'team:')) console.log(key, value);
|
|
54
81
|
|
|
55
82
|
// Record count (native cursor count — no values decoded, but it walks the type's keys)
|
|
56
83
|
const total = okdb.getCount('users');
|
|
57
84
|
```
|
|
58
85
|
|
|
59
86
|
:::warning Iterating across `await`
|
|
60
|
-
The default key-ordered scans — `getRange`, `getKeys`, `getValues`, `getByPrefix` —
|
|
87
|
+
The default key-ordered scans — `getRange`, `getKeys`, `getValues`, `getByPrefix`, and `query()` without an index — read each chunk in a fresh read transaction and resume after the last key: you may `await` inside the loop and keep iterating. The trade-off is that consistency is **per row**, not a point-in-time snapshot — rows written while you are suspended may or may not appear.
|
|
88
|
+
|
|
89
|
+
The **pinned** scans — `byIndex`, `getIndex`, `query()` narrowed by an index, `getChanges`, and any range with `snapshot: true` — read from one point-in-time snapshot. Suspending mid-iteration (an `await` inside the loop) releases it and the next step throws **`READER_HELD_ACROSS_AWAIT`**, deterministically. Either consume them synchronously, materialise first, or opt into `snapshot: 'tolerant'` on `getRange`/`getKeys`/`getValues`/`getChanges` (resume if no commit landed in the meantime, otherwise throw; index scans ignore it):
|
|
61
90
|
|
|
62
|
-
|
|
91
|
+
<!-- continues -->
|
|
63
92
|
|
|
64
93
|
```javascript
|
|
65
94
|
const all = Array.from(okdb.byIndex('users', ['role'], { prefix: ['admin'] }));
|
|
66
|
-
await
|
|
95
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
67
96
|
// safe to use `all` here
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
for (const row of okdb.byIndex('users', ['role'])) {
|
|
100
|
+
await new Promise((resolve) => setTimeout(resolve, 10)); // suspends mid-scan
|
|
101
|
+
}
|
|
102
|
+
} catch (err) {
|
|
103
|
+
console.log(err.code); // 'READER_HELD_ACROSS_AWAIT'
|
|
104
|
+
}
|
|
68
105
|
```
|
|
69
106
|
|
|
70
107
|
See [Upgrading to 2.1](upgrade-2.1.md) for the background.
|
|
@@ -74,12 +111,14 @@ See [Upgrading to 2.1](upgrade-2.1.md) for the background.
|
|
|
74
111
|
|
|
75
112
|
## MongoDB-style query
|
|
76
113
|
|
|
77
|
-
`query()` applies a [sift](https://github.com/crcn/sift.js)
|
|
114
|
+
`query()` applies a MongoDB-style filter (the [sift](https://github.com/crcn/sift.js) operator set) over a range scan. It returns a lazy iterable of `{ key, value }` rows (spread it for an array); `limit`/`offset` count result rows, and `select: (row) => …` maps each row. Geo queries (`near`, `$near`, `$within`) return an Array.
|
|
78
115
|
|
|
79
116
|
Supported operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$exists`, `$regex` (+ `$options`), `$mod`, `$size`, `$all`, `$type`, `$elemMatch`, `$not`, `$and`, `$or`, `$nor`, plus dotted field paths.
|
|
80
117
|
|
|
81
118
|
**`$where` is not supported.** It evaluates code (a string compiled with `new Function`, or a function), so it is rejected everywhere a filter is accepted — `query()`/`count`, the HTTP query and count routes, FTS/vector post-filters, view definitions and subscription filters — at any nesting depth, with `QUERY_OPERATOR_FORBIDDEN` (HTTP 400). Filter in application code instead (e.g. `.filter()` over the results).
|
|
82
119
|
|
|
120
|
+
<!-- continues -->
|
|
121
|
+
|
|
83
122
|
```javascript
|
|
84
123
|
// Basic equality
|
|
85
124
|
const admins = okdb.query('users', { role: 'admin' });
|
|
@@ -103,9 +142,11 @@ const results = okdb.query('users', {
|
|
|
103
142
|
|
|
104
143
|
Without an index hint, `query()` scans every record. With one, it uses the index to iterate only matching entries:
|
|
105
144
|
|
|
145
|
+
<!-- continues -->
|
|
146
|
+
|
|
106
147
|
```javascript
|
|
107
148
|
// Only scans records where role === 'admin'
|
|
108
|
-
const
|
|
149
|
+
const adminsOver30 = okdb.query(
|
|
109
150
|
'users',
|
|
110
151
|
{ role: 'admin', age: { $gte: 30 } },
|
|
111
152
|
{
|
|
@@ -127,8 +168,8 @@ const recent = okdb.query(
|
|
|
127
168
|
);
|
|
128
169
|
|
|
129
170
|
// Arbitrary (non-prefix) range on an index: use startIndex/endIndex, not start/end —
|
|
130
|
-
// query()'s own bound names differ from byIndex's (see below).
|
|
131
|
-
// throws
|
|
171
|
+
// query()'s own bound names differ from byIndex's (see below). start/end are NOT query()
|
|
172
|
+
// options: query() throws if you pass them.
|
|
132
173
|
const weekAgo = Date.now() - 7 * 86400_000;
|
|
133
174
|
const recentAdmins = okdb.query(
|
|
134
175
|
'users',
|
|
@@ -146,16 +187,21 @@ There is no query planner. If you pass `index`, OKDB uses it without cost analys
|
|
|
146
187
|
:::
|
|
147
188
|
|
|
148
189
|
:::warning Unrecognized options throw
|
|
149
|
-
`query()`'s options are a fixed
|
|
190
|
+
`query()`'s options are a fixed vocabulary (`index`, `prefix`, `startIndex`, `endIndex`, `startKey`, `endKey`, `reverse`, `limit`, `offset`, `select`, `near`, `fts`, `vector`, `transaction`) — not a raw pass-through to the underlying range scan. Any other key throws immediately rather than being silently ignored: `start`/`end` (the byIndex/getRange names) with `query() does not support "start"/"end" …`, anything else with `query(): unrecognized option "<key>" … Allowed: …`, and an unknown key inside the nested `index: { fields, prefix, start, end, startKey, endKey }` form with `query(): unrecognized key "<key>" in options.index …`. `byIndex()` and `getRange()` reject unknown options with `UNKNOWN_RANGE_OPTION`.
|
|
150
191
|
:::
|
|
151
192
|
|
|
152
193
|
---
|
|
153
194
|
|
|
154
195
|
## Index scans
|
|
155
196
|
|
|
156
|
-
`byIndex` iterates entries in index order, returning `{ key, value, version, indexKey }`.
|
|
197
|
+
`byIndex` iterates entries in index order, returning `{ key, value, version, indexKey }`. `indexKey` is the stored index key: the indexed field values followed by a trailing `null` sentinel (`['x', null]` for a one-field index, `['x', 3, null]` for two fields), as in 2.x.
|
|
157
198
|
|
|
158
199
|
```javascript
|
|
200
|
+
await okdb.ensureType('leaderboard', { indexes: [['score']] });
|
|
201
|
+
await okdb.ensureType('articles', { indexes: [['author'], ['author', 'publishedAt']] });
|
|
202
|
+
await okdb.put('leaderboard', 'p1', { name: 'Ada', score: 90 });
|
|
203
|
+
await okdb.put('articles', 'a1', { title: 'Hello', author: 'alice', publishedAt: Date.now() });
|
|
204
|
+
|
|
159
205
|
// All records in order of the 'score' field
|
|
160
206
|
for (const { key, value, indexKey } of okdb.byIndex('leaderboard', ['score'], { reverse: true, limit: 10 })) {
|
|
161
207
|
console.log(key, value.name, indexKey[0]);
|
|
@@ -164,14 +210,18 @@ for (const { key, value, indexKey } of okdb.byIndex('leaderboard', ['score'], {
|
|
|
164
210
|
// Exact prefix match: all articles by author 'alice'
|
|
165
211
|
for (const { key, value } of okdb.byIndex('articles', ['author'], {
|
|
166
212
|
prefix: ['alice'],
|
|
167
|
-
})) {
|
|
213
|
+
})) {
|
|
214
|
+
console.log(key, value.title);
|
|
215
|
+
}
|
|
168
216
|
|
|
169
217
|
// Range on composite index: articles by 'alice' published in the last week
|
|
170
218
|
const since = Date.now() - 7 * 86400_000;
|
|
171
219
|
for (const { key, value } of okdb.byIndex('articles', ['author', 'publishedAt'], {
|
|
172
|
-
start:
|
|
173
|
-
end:
|
|
174
|
-
})) {
|
|
220
|
+
start: ['alice', since],
|
|
221
|
+
end: ['alice', Infinity],
|
|
222
|
+
})) {
|
|
223
|
+
console.log(key, value.title);
|
|
224
|
+
}
|
|
175
225
|
```
|
|
176
226
|
|
|
177
227
|
### Options
|
|
@@ -199,6 +249,9 @@ for (const { key, value } of okdb.byIndex('articles', ['author', 'publishedAt'],
|
|
|
199
249
|
Pass `{start, end}` directly, same as `byIndex`. Use `OKDB.HIGH_SENTINEL` as the end bound for prefix scans:
|
|
200
250
|
|
|
201
251
|
```javascript
|
|
252
|
+
await okdb.ensureType('orders', { indexes: [['status'], ['status', 'createdAt']] });
|
|
253
|
+
await okdb.put('orders', 'o1', { status: 'pending', createdAt: Date.now() });
|
|
254
|
+
|
|
202
255
|
// Count orders with status === 'pending'
|
|
203
256
|
const n = okdb.countByIndex('orders', ['status'], {
|
|
204
257
|
start: ['pending'],
|
|
@@ -226,6 +279,18 @@ const open = okdb.countByIndex('orders', ['status', 'createdAt'], {
|
|
|
226
279
|
### FTS signal
|
|
227
280
|
|
|
228
281
|
```javascript
|
|
282
|
+
// Setup for the FTS examples
|
|
283
|
+
await okdb.registerType('articles');
|
|
284
|
+
await okdb.registerIndex('articles', ['status']);
|
|
285
|
+
await okdb.fts.register('articles', 'articles_fts', { fields: ['title', 'body'] });
|
|
286
|
+
await okdb.put('articles', 'a1', {
|
|
287
|
+
title: 'Database indexing basics',
|
|
288
|
+
body: '...',
|
|
289
|
+
status: 'published',
|
|
290
|
+
category: 'tech',
|
|
291
|
+
});
|
|
292
|
+
await okdb.fts.flush('articles'); // wait until the write is searchable
|
|
293
|
+
|
|
229
294
|
// Full-text search — results ordered by BM25 relevance across ALL matches
|
|
230
295
|
const results = await okdb.query(
|
|
231
296
|
'articles',
|
|
@@ -235,16 +300,18 @@ const results = await okdb.query(
|
|
|
235
300
|
limit: 20,
|
|
236
301
|
},
|
|
237
302
|
);
|
|
238
|
-
// Each result has: { key, value, ftsScore, numTerms, maxScore }
|
|
303
|
+
// Each result has: { key, value, version, score, ftsScore, numTerms, maxScore }
|
|
239
304
|
```
|
|
240
305
|
|
|
241
306
|
### FTS + index constraint
|
|
242
307
|
|
|
243
308
|
The index acts as a **hard constraint** — only documents present in the index range are returned. It does not affect ranking.
|
|
244
309
|
|
|
310
|
+
<!-- continues -->
|
|
311
|
+
|
|
245
312
|
```javascript
|
|
246
313
|
// FTS results, but only from published articles
|
|
247
|
-
const
|
|
314
|
+
const published = await okdb.query(
|
|
248
315
|
'articles',
|
|
249
316
|
{},
|
|
250
317
|
{
|
|
@@ -259,8 +326,10 @@ const results = await okdb.query(
|
|
|
259
326
|
|
|
260
327
|
The sift filter narrows the ranked FTS stream: candidates are pulled best-first until `limit` rows pass (or the matches run out), so a selective filter never starves the page:
|
|
261
328
|
|
|
329
|
+
<!-- continues -->
|
|
330
|
+
|
|
262
331
|
```javascript
|
|
263
|
-
const
|
|
332
|
+
const techOnly = await okdb.query(
|
|
264
333
|
'articles',
|
|
265
334
|
{ category: 'tech' },
|
|
266
335
|
{
|
|
@@ -274,6 +343,8 @@ const results = await okdb.query(
|
|
|
274
343
|
|
|
275
344
|
When both `fts` and `vector` are provided, candidates from each signal are combined and re-ranked using **Reciprocal Rank Fusion (RRF)**: `score = Σ weight / (60 + rank)`, each signal ranked within the rows that pass the filter/index constraint. RRF works across incomparable score scales — no normalization needed. `fts.weight` / `vector.weight` (default 1) tilt the fusion toward one signal.
|
|
276
345
|
|
|
346
|
+
<!-- not-runnable: needs an embeddings engine with an ML model -->
|
|
347
|
+
|
|
277
348
|
```javascript
|
|
278
349
|
const results = await okdb.query(
|
|
279
350
|
'articles',
|
|
@@ -300,7 +371,7 @@ embedded field). `limit` counts documents, never chunks.
|
|
|
300
371
|
| `fts` | BM25 relevance | Yes | Posting list intersection, BM25 top-k |
|
|
301
372
|
| `vector` | Similarity score | No — K-bounded | ANN search, approximate |
|
|
302
373
|
|
|
303
|
-
**Important:** `query()` returns a **Promise** when `fts` or `vector` is present (vector search requires async embedding inference). Without these options, `query()`
|
|
374
|
+
**Important:** `query()` returns a **Promise** (of an Array) when `fts` or `vector` is present (vector search requires async embedding inference). Without these options, `query()` returns synchronously.
|
|
304
375
|
|
|
305
376
|
### FTS options
|
|
306
377
|
|
|
@@ -328,10 +399,10 @@ The `index` option accepts a nested object for clarity:
|
|
|
328
399
|
|
|
329
400
|
```javascript
|
|
330
401
|
// Nested form (preferred for hybrid queries)
|
|
331
|
-
{ index: { fields: ['status'], prefix: ['active'] } }
|
|
402
|
+
const nested = { index: { fields: ['status'], prefix: ['active'] } };
|
|
332
403
|
|
|
333
404
|
// Flat form (still works — backward compatible)
|
|
334
|
-
{ index: ['status'], prefix: ['active'] }
|
|
405
|
+
const flat = { index: ['status'], prefix: ['active'] };
|
|
335
406
|
```
|
|
336
407
|
|
|
337
408
|
---
|
|
@@ -341,6 +412,7 @@ The `index` option accepts a nested object for clarity:
|
|
|
341
412
|
OKDB has a built-in geospatial index based on geohash. Register a geo index on a field that stores a `{ lat, lon }` object (numbers, in degrees). Other shapes — e.g. an `[lat, lon]` array or GeoJSON — are not recognised and the document is silently left out of geo results:
|
|
342
413
|
|
|
343
414
|
```javascript
|
|
415
|
+
await okdb.registerType('places');
|
|
344
416
|
await okdb.registerIndex('places', ['location'], { type: 'geo', precision: 7 });
|
|
345
417
|
|
|
346
418
|
// Store records with lat/lon
|
|
@@ -357,7 +429,7 @@ for (const { key, value, distance } of nearby) {
|
|
|
357
429
|
}
|
|
358
430
|
```
|
|
359
431
|
|
|
360
|
-
Internally, geohash prefix expansion covers the radius at the registered precision. Precision 7 gives ~
|
|
432
|
+
Internally, geohash prefix expansion covers the radius at the registered precision. Precision 7 gives ~153 m cells — good for neighbourhood/city-level queries. For ~5 m cells, use precision 9 (see the precision guide in [Indexes](./indexes.md#geo-indexes)).
|
|
361
433
|
|
|
362
434
|
---
|
|
363
435
|
|
|
@@ -372,6 +444,7 @@ Most scan methods accept the same range options bag:
|
|
|
372
444
|
limit?: number; // max entries returned
|
|
373
445
|
offset?: number; // entries to skip
|
|
374
446
|
reverse?: boolean; // descending order
|
|
375
|
-
prefix?: any[]; // index prefix (byIndex / query
|
|
447
|
+
prefix?: any[]; // index prefix (byIndex / getIndex / countByIndex / query)
|
|
448
|
+
snapshot?: boolean | 'tolerant'; // getRange / getKeys / getValues: pin one snapshot (see above)
|
|
376
449
|
}
|
|
377
450
|
```
|