@loradb/lora-node 0.36.0 → 0.36.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 +5 -0
- package/docs/README.md +86 -0
- package/docs/concepts/graph-model.md +270 -0
- package/docs/concepts/nodes.md +285 -0
- package/docs/concepts/properties.md +348 -0
- package/docs/concepts/relationships.md +325 -0
- package/docs/concepts/result-formats.md +183 -0
- package/docs/concepts/schema-free.md +183 -0
- package/docs/cookbook.md +1081 -0
- package/docs/data-types/lists-and-maps.md +406 -0
- package/docs/data-types/overview.md +210 -0
- package/docs/data-types/scalars.md +376 -0
- package/docs/data-types/spatial.md +291 -0
- package/docs/data-types/temporal.md +355 -0
- package/docs/data-types/vectors.md +563 -0
- package/docs/errors.md +183 -0
- package/docs/functions/aggregation.md +372 -0
- package/docs/functions/list.md +522 -0
- package/docs/functions/map.md +207 -0
- package/docs/functions/math.md +421 -0
- package/docs/functions/number.md +197 -0
- package/docs/functions/overview.md +545 -0
- package/docs/functions/spatial.md +384 -0
- package/docs/functions/string.md +502 -0
- package/docs/functions/temporal.md +590 -0
- package/docs/functions/utility.md +137 -0
- package/docs/functions/vectors.md +772 -0
- package/docs/getting-started/installation.md +204 -0
- package/docs/getting-started/node.md +582 -0
- package/docs/getting-started/tutorial.md +334 -0
- package/docs/index.md +203 -0
- package/docs/limitations.md +291 -0
- package/docs/performance.md +219 -0
- package/docs/queries/aggregation.md +520 -0
- package/docs/queries/cheat-sheet.md +302 -0
- package/docs/queries/constraints.md +239 -0
- package/docs/queries/create.md +331 -0
- package/docs/queries/examples.md +453 -0
- package/docs/queries/index.md +169 -0
- package/docs/queries/indexes.md +546 -0
- package/docs/queries/match.md +429 -0
- package/docs/queries/ordering.md +359 -0
- package/docs/queries/parameters.md +328 -0
- package/docs/queries/paths.md +462 -0
- package/docs/queries/return-with.md +500 -0
- package/docs/queries/set-delete.md +369 -0
- package/docs/queries/unwind-merge.md +358 -0
- package/docs/queries/where.md +416 -0
- package/docs/snapshot.md +545 -0
- package/docs/troubleshooting.md +1158 -0
- package/docs/wal.md +570 -0
- package/docs/why.md +273 -0
- package/package.json +13 -14
package/docs/cookbook.md
ADDED
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "LoraDB Query Cookbook"
|
|
3
|
+
description: "Scenario-driven Cypher recipes for LoraDB — social graphs, e-commerce, event streams, and geospatial queries — each with a concrete data model and working query."
|
|
4
|
+
online: "https://loradb.com/docs/cookbook"
|
|
5
|
+
package: "@loradb/lora-node@0.36.2"
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# LoraDB Query Cookbook
|
|
9
|
+
|
|
10
|
+
A scenario-driven companion to the clause-by-clause
|
|
11
|
+
[**Queries reference**](./queries/index.md). Reach for this page when you
|
|
12
|
+
know the question ("who are my mutual follows?", "which orders are
|
|
13
|
+
late?") but aren't sure how to shape the Cypher. Where the reference
|
|
14
|
+
answers *"what does this clause do"*, the cookbook answers *"how do
|
|
15
|
+
I ask this question"*.
|
|
16
|
+
|
|
17
|
+
Each recipe names a real problem, states its assumed data model,
|
|
18
|
+
gives a query, and explains why it works — then lists useful
|
|
19
|
+
variations and related concepts. Recipes are grouped by domain:
|
|
20
|
+
social, e-commerce, events, geospatial, vector retrieval. Every
|
|
21
|
+
query is idiomatic LoraDB — no external utility procedures, no `CALL`, no window functions
|
|
22
|
+
— and when a SQL idiom doesn't translate, the recipe shows the
|
|
23
|
+
Cypher-native shape.
|
|
24
|
+
|
|
25
|
+
## On this page
|
|
26
|
+
|
|
27
|
+
- [Social graph patterns](#social-graph-patterns)
|
|
28
|
+
- [E-commerce patterns](#e-commerce-patterns)
|
|
29
|
+
- [Event / time-based patterns](#event--time-based-patterns)
|
|
30
|
+
- [Geospatial patterns](#geospatial-patterns)
|
|
31
|
+
- [Vector-retrieval patterns](#vector-retrieval-patterns)
|
|
32
|
+
- [Backup and restore](#backup-and-restore)
|
|
33
|
+
- [See also](#see-also)
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Social graph patterns
|
|
38
|
+
|
|
39
|
+
### Recipe: Friends of friends
|
|
40
|
+
|
|
41
|
+
#### Problem
|
|
42
|
+
|
|
43
|
+
"For user `$id`, list people they don't follow yet, but who are
|
|
44
|
+
followed by somebody they do follow."
|
|
45
|
+
|
|
46
|
+
#### Assumed data model
|
|
47
|
+
|
|
48
|
+
- `:User {id, handle}`
|
|
49
|
+
- `(u:User)-[:FOLLOWS]->(v:User)` — directed "u follows v"
|
|
50
|
+
|
|
51
|
+
#### Query
|
|
52
|
+
|
|
53
|
+
```cypher
|
|
54
|
+
MATCH (me:User {id: $id})-[:FOLLOWS]->(friend:User)-[:FOLLOWS]->(candidate:User)
|
|
55
|
+
WHERE candidate <> me
|
|
56
|
+
AND NOT EXISTS { (me)-[:FOLLOWS]->(candidate) }
|
|
57
|
+
RETURN candidate.handle,
|
|
58
|
+
count(*) AS shared_paths
|
|
59
|
+
ORDER BY shared_paths DESC
|
|
60
|
+
LIMIT 20
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
#### Explanation
|
|
64
|
+
|
|
65
|
+
The two-hop pattern enumerates every `(me, friend, candidate)`
|
|
66
|
+
triple. `NOT EXISTS` removes candidates `me` already follows;
|
|
67
|
+
`candidate <> me` removes self-loops. `count(*)` becomes the number
|
|
68
|
+
of mutual friends — a useful ranking signal.
|
|
69
|
+
|
|
70
|
+
#### Variations
|
|
71
|
+
|
|
72
|
+
- Also consider follow**ers**: reverse the last segment to
|
|
73
|
+
`(candidate)-[:FOLLOWS]->(friend)`.
|
|
74
|
+
- Combine both directions with a [`UNION`](./queries/return-with.md#union--union-all)
|
|
75
|
+
and dedup with [`collect(DISTINCT …)`](./functions/aggregation.md#collect).
|
|
76
|
+
- Weight by recency of `friend`'s follow using a `:FOLLOWS {since}`
|
|
77
|
+
property — see the e-commerce [co-purchase recipe](#recipe-co-purchase-patterns).
|
|
78
|
+
|
|
79
|
+
#### Related concepts
|
|
80
|
+
|
|
81
|
+
- [MATCH — multi-hop patterns](./queries/match.md#multi-hop-patterns)
|
|
82
|
+
- [WHERE — pattern existence](./queries/where.md#pattern-existence)
|
|
83
|
+
- [Aggregation — count](./queries/aggregation.md#count)
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
### Recipe: Mutual connections
|
|
88
|
+
|
|
89
|
+
#### Problem
|
|
90
|
+
|
|
91
|
+
"List pairs of users who follow each other."
|
|
92
|
+
|
|
93
|
+
#### Assumed data model
|
|
94
|
+
|
|
95
|
+
- `:User`
|
|
96
|
+
- `(a)-[:FOLLOWS]->(b)` — directed
|
|
97
|
+
|
|
98
|
+
#### Query
|
|
99
|
+
|
|
100
|
+
```cypher
|
|
101
|
+
MATCH (a:User)-[:FOLLOWS]->(b:User)-[:FOLLOWS]->(a)
|
|
102
|
+
WHERE id(a) < id(b)
|
|
103
|
+
RETURN a.handle, b.handle
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
#### Explanation
|
|
107
|
+
|
|
108
|
+
The pattern reads "a follows b and b follows a" — a 2-cycle. The
|
|
109
|
+
`id(a) < id(b)` predicate keeps one row per unordered pair; without
|
|
110
|
+
it you'd get both `(alice, bob)` and `(bob, alice)`.
|
|
111
|
+
|
|
112
|
+
#### Variations
|
|
113
|
+
|
|
114
|
+
- Add a property filter: only mutuals where both accounts are
|
|
115
|
+
active — add `WHERE a.active AND b.active`.
|
|
116
|
+
- Rank by "oldest mutuals first" by collecting the relationship:
|
|
117
|
+
`MATCH (a)-[r1:FOLLOWS]->(b)-[r2:FOLLOWS]->(a)` and order by
|
|
118
|
+
`min(r1.since, r2.since)` — see
|
|
119
|
+
[ORDER BY](./queries/ordering.md#ordering-by-computed-expression).
|
|
120
|
+
|
|
121
|
+
#### Related concepts
|
|
122
|
+
|
|
123
|
+
- [Nodes → id() usage](./functions/overview.md#entity-introspection)
|
|
124
|
+
- [Concepts → relationships direction conventions](./concepts/relationships.md#direction-conventions)
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
### Recipe: Recommendations via second-degree connections
|
|
129
|
+
|
|
130
|
+
#### Problem
|
|
131
|
+
|
|
132
|
+
"Recommend accounts for `$id` to follow, ranked by how many of their
|
|
133
|
+
current follows already follow that account."
|
|
134
|
+
|
|
135
|
+
#### Assumed data model
|
|
136
|
+
|
|
137
|
+
- `:User`
|
|
138
|
+
- `(u)-[:FOLLOWS]->(v)`
|
|
139
|
+
|
|
140
|
+
#### Query
|
|
141
|
+
|
|
142
|
+
```cypher
|
|
143
|
+
MATCH (me:User {id: $id})-[:FOLLOWS]->(:User)-[:FOLLOWS]->(rec:User)
|
|
144
|
+
WHERE rec <> me
|
|
145
|
+
AND NOT EXISTS { (me)-[:FOLLOWS]->(rec) }
|
|
146
|
+
RETURN rec.handle,
|
|
147
|
+
count(*) AS score,
|
|
148
|
+
collect(DISTINCT rec.country)[..3] AS sample_countries
|
|
149
|
+
ORDER BY score DESC
|
|
150
|
+
LIMIT 10
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
#### Explanation
|
|
154
|
+
|
|
155
|
+
Similar to [friends-of-friends](#recipe-friends-of-friends) but
|
|
156
|
+
projects a richer result — the count becomes a recommendation score,
|
|
157
|
+
and we collect a diverse sample of metadata. `[..3]` slices the
|
|
158
|
+
collected list to the first three entries — a
|
|
159
|
+
[list slice](./functions/list.md#indexing-and-slicing).
|
|
160
|
+
|
|
161
|
+
#### Variations
|
|
162
|
+
|
|
163
|
+
- Add a CASE-based boost for accounts with a `verified` badge:
|
|
164
|
+
`count(CASE WHEN rec.verified THEN 1 END) * 2 + count(*)`.
|
|
165
|
+
- Expand to 3-hop with `[:FOLLOWS*2..3]` — bound it to avoid
|
|
166
|
+
run-away — see [Paths → variable-length](./queries/paths.md#variable-length-relationships).
|
|
167
|
+
|
|
168
|
+
#### Related concepts
|
|
169
|
+
|
|
170
|
+
- [CASE expressions](./queries/return-with.md#case-expressions)
|
|
171
|
+
- [Count-if via CASE](./queries/aggregation.md#conditional-count-count-if)
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
### Recipe: Influence score (weighted walk)
|
|
176
|
+
|
|
177
|
+
#### Problem
|
|
178
|
+
|
|
179
|
+
"For each user, estimate an influence score based on how many
|
|
180
|
+
followers reach them within two hops."
|
|
181
|
+
|
|
182
|
+
#### Assumed data model
|
|
183
|
+
|
|
184
|
+
- `:User`
|
|
185
|
+
- `(follower)-[:FOLLOWS]->(followee)` — standard directed follow
|
|
186
|
+
|
|
187
|
+
#### Query
|
|
188
|
+
|
|
189
|
+
```cypher
|
|
190
|
+
MATCH (u:User)
|
|
191
|
+
OPTIONAL MATCH (u)<-[:FOLLOWS*1..2]-(reacher:User)
|
|
192
|
+
RETURN u.handle,
|
|
193
|
+
count(DISTINCT reacher) AS reach
|
|
194
|
+
ORDER BY reach DESC
|
|
195
|
+
LIMIT 20
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
#### Explanation
|
|
199
|
+
|
|
200
|
+
`OPTIONAL MATCH` preserves users with zero reach. `count(DISTINCT
|
|
201
|
+
reacher)` avoids double-counting any user reached through multiple
|
|
202
|
+
paths. Bounded at two hops to stay tractable.
|
|
203
|
+
|
|
204
|
+
#### Variations
|
|
205
|
+
|
|
206
|
+
- Replace `reacher` with `count(DISTINCT path.length(p))` paths of
|
|
207
|
+
different lengths to reveal reach-at-each-distance.
|
|
208
|
+
- Combine with `:FOLLOWS {since}` weights:
|
|
209
|
+
`sum(math.exp(-temporal.in_days(r.since, temporal.today()) * 0.02))`
|
|
210
|
+
when `since` is a `DATE`.
|
|
211
|
+
|
|
212
|
+
#### Related concepts
|
|
213
|
+
|
|
214
|
+
- [OPTIONAL MATCH with aggregation](./queries/match.md#optional-match-with-aggregation)
|
|
215
|
+
- [count(expr)](./functions/aggregation.md#count)
|
|
216
|
+
|
|
217
|
+
---
|
|
218
|
+
|
|
219
|
+
## E-commerce patterns
|
|
220
|
+
|
|
221
|
+
### Recipe: Top N products by revenue
|
|
222
|
+
|
|
223
|
+
#### Problem
|
|
224
|
+
|
|
225
|
+
"The ten products with the highest paid-order revenue this month."
|
|
226
|
+
|
|
227
|
+
#### Assumed data model
|
|
228
|
+
|
|
229
|
+
- `:Product {id, name, price}`
|
|
230
|
+
- `:Order {id, placed_at, status}`
|
|
231
|
+
- `(o)-[:CONTAINS {quantity}]->(p)`
|
|
232
|
+
|
|
233
|
+
#### Query
|
|
234
|
+
|
|
235
|
+
```cypher
|
|
236
|
+
MATCH (o:Order)-[c:CONTAINS]->(p:Product)
|
|
237
|
+
WHERE o.status = 'paid'
|
|
238
|
+
AND o.placed_at >= temporal.truncate('month', temporal.today())
|
|
239
|
+
RETURN p.name,
|
|
240
|
+
sum(c.quantity * p.price) AS revenue,
|
|
241
|
+
sum(c.quantity) AS units,
|
|
242
|
+
count(DISTINCT o) AS orders
|
|
243
|
+
ORDER BY revenue DESC
|
|
244
|
+
LIMIT 10
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
#### Explanation
|
|
248
|
+
|
|
249
|
+
Joins orders and products through the `:CONTAINS` edge, filters to
|
|
250
|
+
paid orders in the current month, then aggregates revenue per
|
|
251
|
+
product. `count(DISTINCT o)` captures orders (an order can contain
|
|
252
|
+
many items), distinct from the total `units` sold.
|
|
253
|
+
|
|
254
|
+
#### Variations
|
|
255
|
+
|
|
256
|
+
- Top-N per category: group by `p.category` as well and then
|
|
257
|
+
pick-first within each using
|
|
258
|
+
[`collect(…)[..1]`](./queries/aggregation.md#top-contributor-per-group-pipeline-trick).
|
|
259
|
+
- Year-to-date: replace the date filter with
|
|
260
|
+
`o.placed_at >= temporal.truncate('year', temporal.today())`.
|
|
261
|
+
|
|
262
|
+
#### Related concepts
|
|
263
|
+
|
|
264
|
+
- [Aggregation walkthrough](./queries/aggregation.md#a-five-step-walkthrough)
|
|
265
|
+
- [Temporal → truncation](./functions/temporal.md#truncation)
|
|
266
|
+
|
|
267
|
+
---
|
|
268
|
+
|
|
269
|
+
### Recipe: Co-purchase patterns
|
|
270
|
+
|
|
271
|
+
#### Problem
|
|
272
|
+
|
|
273
|
+
"Which products are frequently bought together with `$sku`?"
|
|
274
|
+
|
|
275
|
+
#### Assumed data model
|
|
276
|
+
|
|
277
|
+
- `:Product {sku}`
|
|
278
|
+
- `:Order`
|
|
279
|
+
- `(o)-[:CONTAINS]->(p)`
|
|
280
|
+
|
|
281
|
+
#### Query
|
|
282
|
+
|
|
283
|
+
```cypher
|
|
284
|
+
MATCH (anchor:Product {sku: $sku})<-[:CONTAINS]-(:Order)-[:CONTAINS]->(other:Product)
|
|
285
|
+
WHERE other <> anchor
|
|
286
|
+
RETURN other.sku,
|
|
287
|
+
count(*) AS co_orders
|
|
288
|
+
ORDER BY co_orders DESC
|
|
289
|
+
LIMIT 20
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
#### Explanation
|
|
293
|
+
|
|
294
|
+
Traverses orders that contain the anchor product and jumps to other
|
|
295
|
+
products in the same order. `count(*)` is the number of orders in
|
|
296
|
+
which the co-occurrence happened.
|
|
297
|
+
|
|
298
|
+
#### Variations
|
|
299
|
+
|
|
300
|
+
- Only ship-completed orders: add `WHERE o.status = 'shipped'` after
|
|
301
|
+
binding `(o:Order)`.
|
|
302
|
+
- Lift score over per-product baseline:
|
|
303
|
+
`count(*) * 1.0 / ((MATCH (:Order)-[:CONTAINS]->(anchor)…))` — two
|
|
304
|
+
stages combined via `WITH` — see
|
|
305
|
+
[Aggregation → pipeline aggregation](./queries/aggregation.md#pipeline-aggregation).
|
|
306
|
+
|
|
307
|
+
#### Related concepts
|
|
308
|
+
|
|
309
|
+
- [WHERE — pattern filters](./queries/where.md#pattern-existence)
|
|
310
|
+
- [Ordering — Top-N](./queries/ordering.md#top-n)
|
|
311
|
+
|
|
312
|
+
---
|
|
313
|
+
|
|
314
|
+
### Recipe: Repeat buyers
|
|
315
|
+
|
|
316
|
+
#### Problem
|
|
317
|
+
|
|
318
|
+
"Users who placed more than one paid order."
|
|
319
|
+
|
|
320
|
+
#### Assumed data model
|
|
321
|
+
|
|
322
|
+
- `:User`
|
|
323
|
+
- `:Order {status}`
|
|
324
|
+
- `(u)-[:PLACED]->(o)`
|
|
325
|
+
|
|
326
|
+
#### Query
|
|
327
|
+
|
|
328
|
+
```cypher
|
|
329
|
+
MATCH (u:User)-[:PLACED]->(o:Order {status: 'paid'})
|
|
330
|
+
WITH u, count(o) AS orders
|
|
331
|
+
WHERE orders > 1
|
|
332
|
+
RETURN u.email,
|
|
333
|
+
orders
|
|
334
|
+
ORDER BY orders DESC
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
#### Explanation
|
|
338
|
+
|
|
339
|
+
Classic HAVING-style pipeline: aggregate first, then filter the
|
|
340
|
+
aggregated column. Cypher has no `HAVING` keyword — pipe through
|
|
341
|
+
[`WITH`](./queries/return-with.md#with) instead.
|
|
342
|
+
|
|
343
|
+
#### Variations
|
|
344
|
+
|
|
345
|
+
- Lifetime value: replace `count(o)` with `sum(o.amount)`.
|
|
346
|
+
- Last-purchase recency: add `max(o.placed_at) AS last` and
|
|
347
|
+
filter on that.
|
|
348
|
+
|
|
349
|
+
#### Related concepts
|
|
350
|
+
|
|
351
|
+
- [HAVING-style filtering](./queries/return-with.md#having-style-filtering-with)
|
|
352
|
+
- [MERGE upsert patterns](./queries/unwind-merge.md#merge)
|
|
353
|
+
|
|
354
|
+
---
|
|
355
|
+
|
|
356
|
+
### Recipe: Cart abandonment
|
|
357
|
+
|
|
358
|
+
#### Problem
|
|
359
|
+
|
|
360
|
+
"Users with an open cart containing more than `$n` items, but no
|
|
361
|
+
order placed in the last 30 days."
|
|
362
|
+
|
|
363
|
+
#### Assumed data model
|
|
364
|
+
|
|
365
|
+
- `:User`
|
|
366
|
+
- `:Cart {status}`, `:Item`
|
|
367
|
+
- `(u)-[:HAS_CART]->(c)`, `(c)-[:CONTAINS]->(:Item)`, `(u)-[:PLACED]->(:Order)`
|
|
368
|
+
|
|
369
|
+
#### Query
|
|
370
|
+
|
|
371
|
+
```cypher
|
|
372
|
+
MATCH (u:User)-[:HAS_CART]->(c:Cart {status: 'open'})-[:CONTAINS]->(i:Item)
|
|
373
|
+
WITH u, c, count(i) AS items
|
|
374
|
+
WHERE items > $n
|
|
375
|
+
OPTIONAL MATCH (u)-[:PLACED]->(o:Order)
|
|
376
|
+
WITH u, c, items, max(o.placed_at) AS last_order_at
|
|
377
|
+
WHERE last_order_at IS NULL
|
|
378
|
+
OR last_order_at < temporal.now() - 'P30D'::DURATION
|
|
379
|
+
RETURN u.email, c.id, items
|
|
380
|
+
ORDER BY items DESC
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
#### Explanation
|
|
384
|
+
|
|
385
|
+
The `NOT EXISTS { }` sub-pattern is an anti-join — keeps users
|
|
386
|
+
without any recent order. The surrounding pipeline filters open
|
|
387
|
+
carts above the threshold size.
|
|
388
|
+
|
|
389
|
+
#### Variations
|
|
390
|
+
|
|
391
|
+
- Add recency of cart update:
|
|
392
|
+
`AND c.updated_at >= temporal.now() - 'P7D'::DURATION` for "stale but
|
|
393
|
+
not abandoned".
|
|
394
|
+
- Compute total cart value: `sum(i.price * i.quantity) AS total`.
|
|
395
|
+
|
|
396
|
+
#### Related concepts
|
|
397
|
+
|
|
398
|
+
- [Pattern existence with NOT EXISTS](./queries/where.md#pattern-existence)
|
|
399
|
+
- [Temporal arithmetic](./functions/temporal.md#arithmetic)
|
|
400
|
+
|
|
401
|
+
---
|
|
402
|
+
|
|
403
|
+
## Event / time-based patterns
|
|
404
|
+
|
|
405
|
+
### Recipe: Attendees per event
|
|
406
|
+
|
|
407
|
+
#### Problem
|
|
408
|
+
|
|
409
|
+
"Total and unique attendees for each upcoming event, plus a flag
|
|
410
|
+
for whether the event is sold out."
|
|
411
|
+
|
|
412
|
+
#### Assumed data model
|
|
413
|
+
|
|
414
|
+
- `:Event {id, starts_at, capacity}`
|
|
415
|
+
- `:User`
|
|
416
|
+
- `(u)-[:RSVP {status}]->(e)`
|
|
417
|
+
|
|
418
|
+
#### Query
|
|
419
|
+
|
|
420
|
+
```cypher
|
|
421
|
+
MATCH (e:Event)
|
|
422
|
+
WHERE e.starts_at >= temporal.now()
|
|
423
|
+
OPTIONAL MATCH (u:User)-[r:RSVP {status: 'yes'}]->(e)
|
|
424
|
+
WITH e, count(u) AS going
|
|
425
|
+
RETURN e.id,
|
|
426
|
+
e.starts_at,
|
|
427
|
+
going,
|
|
428
|
+
e.capacity,
|
|
429
|
+
CASE
|
|
430
|
+
WHEN going >= e.capacity THEN 'sold_out'
|
|
431
|
+
WHEN going >= e.capacity * 0.8 THEN 'filling'
|
|
432
|
+
ELSE 'open'
|
|
433
|
+
END AS status
|
|
434
|
+
ORDER BY e.starts_at
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
#### Explanation
|
|
438
|
+
|
|
439
|
+
`OPTIONAL MATCH` ensures events with zero RSVPs still appear.
|
|
440
|
+
[`CASE`](./queries/return-with.md#case-expressions) computes a tiered
|
|
441
|
+
status per event.
|
|
442
|
+
|
|
443
|
+
#### Variations
|
|
444
|
+
|
|
445
|
+
- Break out by ticket tier:
|
|
446
|
+
`collect(DISTINCT r.tier) AS tiers`.
|
|
447
|
+
- Include "maybe" RSVPs separately:
|
|
448
|
+
`count(CASE WHEN r.status = 'maybe' THEN 1 END) AS maybes`.
|
|
449
|
+
|
|
450
|
+
#### Related concepts
|
|
451
|
+
|
|
452
|
+
- [CASE expressions](./queries/return-with.md#case-expressions)
|
|
453
|
+
- [OPTIONAL MATCH](./queries/match.md#optional-match)
|
|
454
|
+
|
|
455
|
+
---
|
|
456
|
+
|
|
457
|
+
### Recipe: Events in a rolling window
|
|
458
|
+
|
|
459
|
+
#### Problem
|
|
460
|
+
|
|
461
|
+
"All events between now and `$horizon_days` days in the future, with
|
|
462
|
+
their host."
|
|
463
|
+
|
|
464
|
+
#### Assumed data model
|
|
465
|
+
|
|
466
|
+
- `:Event {starts_at}`
|
|
467
|
+
- `:User` (host)
|
|
468
|
+
- `(u)-[:HOSTS]->(e)`
|
|
469
|
+
|
|
470
|
+
#### Query
|
|
471
|
+
|
|
472
|
+
```cypher
|
|
473
|
+
MATCH (host:User)-[:HOSTS]->(e:Event)
|
|
474
|
+
WHERE e.starts_at >= temporal.now()
|
|
475
|
+
AND e.starts_at < temporal.now() + {days: $horizon_days}::DURATION
|
|
476
|
+
RETURN e.id,
|
|
477
|
+
e.starts_at,
|
|
478
|
+
host.handle
|
|
479
|
+
ORDER BY e.starts_at
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
#### Explanation
|
|
483
|
+
|
|
484
|
+
`{days: $horizon_days}::DURATION` accepts a bound integer —
|
|
485
|
+
`'P7D'::DURATION` only works with a literal string. Use the map
|
|
486
|
+
form whenever the window size is dynamic.
|
|
487
|
+
|
|
488
|
+
#### Variations
|
|
489
|
+
|
|
490
|
+
- Hour-bucket count to drive a chart:
|
|
491
|
+
`temporal.truncate('hour', e.starts_at)` grouped with `count(*)` —
|
|
492
|
+
see [Temporal → bucketing](./functions/temporal.md#bucketing-rows).
|
|
493
|
+
- Timezone-specific: store `starts_at` as `DateTime` (UTC-offset
|
|
494
|
+
aware) — see [Temporal types](./data-types/temporal.md).
|
|
495
|
+
|
|
496
|
+
#### Related concepts
|
|
497
|
+
|
|
498
|
+
- [Temporal truncation](./functions/temporal.md#truncation)
|
|
499
|
+
- [Temporal types](./data-types/temporal.md)
|
|
500
|
+
|
|
501
|
+
---
|
|
502
|
+
|
|
503
|
+
### Recipe: Overlapping attendance
|
|
504
|
+
|
|
505
|
+
#### Problem
|
|
506
|
+
|
|
507
|
+
"For each pair of users who attended at least `$n` common events
|
|
508
|
+
this year, list the events they shared."
|
|
509
|
+
|
|
510
|
+
#### Assumed data model
|
|
511
|
+
|
|
512
|
+
- `:User`, `:Event`
|
|
513
|
+
- `(u)-[:ATTENDED]->(e)` with `e.at: DateTime`
|
|
514
|
+
|
|
515
|
+
#### Query
|
|
516
|
+
|
|
517
|
+
```cypher
|
|
518
|
+
MATCH (a:User)-[:ATTENDED]->(e:Event)<-[:ATTENDED]-(b:User)
|
|
519
|
+
WHERE id(a) < id(b)
|
|
520
|
+
AND e.at >= temporal.truncate('year', temporal.today())
|
|
521
|
+
WITH a, b, collect(DISTINCT e.id) AS shared
|
|
522
|
+
WHERE value.size(shared) >= $n
|
|
523
|
+
RETURN a.handle, b.handle, shared, value.size(shared) AS n_shared
|
|
524
|
+
ORDER BY n_shared DESC
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
#### Explanation
|
|
528
|
+
|
|
529
|
+
The pattern generates all `(a, e, b)` triples for attendees of the
|
|
530
|
+
same event. `id(a) < id(b)` keeps one row per unordered pair.
|
|
531
|
+
`collect(DISTINCT e.id)` deduplicates events (an attendee can't
|
|
532
|
+
attend the same event twice but the pattern could still
|
|
533
|
+
double-count in more complex schemas).
|
|
534
|
+
|
|
535
|
+
#### Variations
|
|
536
|
+
|
|
537
|
+
- Use `count(DISTINCT e)` instead of `value.size(collect(…))` for a
|
|
538
|
+
cheaper pairwise score when you don't need the event ids.
|
|
539
|
+
- Weight events by `e.importance`.
|
|
540
|
+
|
|
541
|
+
#### Related concepts
|
|
542
|
+
|
|
543
|
+
- [Symmetric-pair dedup](./queries/match.md#symmetric-pair-deduplication)
|
|
544
|
+
- [collect → distinct](./functions/aggregation.md#collect)
|
|
545
|
+
|
|
546
|
+
---
|
|
547
|
+
|
|
548
|
+
### Recipe: Cohort retention
|
|
549
|
+
|
|
550
|
+
#### Problem
|
|
551
|
+
|
|
552
|
+
"For each signup-month cohort, what fraction of users logged in
|
|
553
|
+
during the last 30 days?"
|
|
554
|
+
|
|
555
|
+
#### Assumed data model
|
|
556
|
+
|
|
557
|
+
- `:User {id, created}`
|
|
558
|
+
- `:Login {at}`
|
|
559
|
+
- `(u)-[:LOGGED_IN]->(l:Login)`
|
|
560
|
+
|
|
561
|
+
#### Query
|
|
562
|
+
|
|
563
|
+
```cypher
|
|
564
|
+
MATCH (u:User)
|
|
565
|
+
WITH temporal.truncate('month', u.created) AS cohort, u
|
|
566
|
+
OPTIONAL MATCH (u)-[:LOGGED_IN]->(l:Login)
|
|
567
|
+
WHERE l.at >= temporal.now() - 'P30D'::DURATION
|
|
568
|
+
RETURN cohort,
|
|
569
|
+
count(DISTINCT u) AS total,
|
|
570
|
+
count(DISTINCT CASE WHEN l IS NOT NULL THEN u END) AS active_30d,
|
|
571
|
+
toFloat(count(DISTINCT CASE WHEN l IS NOT NULL THEN u END))
|
|
572
|
+
/ count(DISTINCT u) AS retention
|
|
573
|
+
ORDER BY cohort
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
#### Explanation
|
|
577
|
+
|
|
578
|
+
`OPTIONAL MATCH` preserves cohort members who never logged in.
|
|
579
|
+
Counting `DISTINCT u` gives cohort size; the conditional `CASE`
|
|
580
|
+
inside `count(DISTINCT …)` gives the active subset. The division
|
|
581
|
+
yields retention between 0 and 1.
|
|
582
|
+
|
|
583
|
+
#### Variations
|
|
584
|
+
|
|
585
|
+
- Slice by acquisition channel: add
|
|
586
|
+
`WITH cohort, u.channel AS channel, u` and include `channel` in
|
|
587
|
+
the `RETURN`.
|
|
588
|
+
- Wider windows: change `P30D` to `P90D` / `P365D`.
|
|
589
|
+
|
|
590
|
+
#### Related concepts
|
|
591
|
+
|
|
592
|
+
- [Temporal truncation](./functions/temporal.md#truncation)
|
|
593
|
+
- [CASE inside count](./queries/aggregation.md#conditional-count-count-if)
|
|
594
|
+
|
|
595
|
+
---
|
|
596
|
+
|
|
597
|
+
## Geospatial patterns
|
|
598
|
+
|
|
599
|
+
### Recipe: N nearest places
|
|
600
|
+
|
|
601
|
+
#### Problem
|
|
602
|
+
|
|
603
|
+
"Ten nearest venues to `$here`, with distance in metres."
|
|
604
|
+
|
|
605
|
+
#### Assumed data model
|
|
606
|
+
|
|
607
|
+
- `:Venue {id, name, location: Point}` — WGS-84 2D preferred
|
|
608
|
+
|
|
609
|
+
#### Query
|
|
610
|
+
|
|
611
|
+
```cypher
|
|
612
|
+
MATCH (v:Venue)
|
|
613
|
+
WHERE v.location.srid = $here.srid // guard cross-SRID and missing locations
|
|
614
|
+
WITH v, geo.distance(v.location, $here) AS metres
|
|
615
|
+
RETURN v.name, metres
|
|
616
|
+
ORDER BY metres
|
|
617
|
+
LIMIT 10
|
|
618
|
+
```
|
|
619
|
+
|
|
620
|
+
#### Explanation
|
|
621
|
+
|
|
622
|
+
[`geo.distance`](./functions/spatial.md#geodistance) on same-SRID WGS-84
|
|
623
|
+
points returns metres. The SRID guard skips venues stored with a
|
|
624
|
+
different SRID — cross-SRID distance fails the whole query — and venues
|
|
625
|
+
without a location, whose `srid` is `null`.
|
|
626
|
+
|
|
627
|
+
#### Variations
|
|
628
|
+
|
|
629
|
+
- Cluster by kilometre ring:
|
|
630
|
+
`toInteger(metres / 1000) AS km` grouped with `count(*)`.
|
|
631
|
+
- Include only open venues: `WHERE v.status = 'open'` before the
|
|
632
|
+
distance computation.
|
|
633
|
+
|
|
634
|
+
#### Related concepts
|
|
635
|
+
|
|
636
|
+
- [Spatial functions → distance](./functions/spatial.md#geodistance)
|
|
637
|
+
- [Spatial data types](./data-types/spatial.md)
|
|
638
|
+
|
|
639
|
+
---
|
|
640
|
+
|
|
641
|
+
### Recipe: Region / bounding-box filter
|
|
642
|
+
|
|
643
|
+
#### Problem
|
|
644
|
+
|
|
645
|
+
"Every city between latitudes `$s..$n` and longitudes `$w..$e`."
|
|
646
|
+
|
|
647
|
+
#### Assumed data model
|
|
648
|
+
|
|
649
|
+
- `:City {name, location}` — WGS-84 2D
|
|
650
|
+
|
|
651
|
+
#### Query
|
|
652
|
+
|
|
653
|
+
```cypher
|
|
654
|
+
MATCH (c:City)
|
|
655
|
+
WHERE c.location.latitude >= $s AND c.location.latitude <= $n
|
|
656
|
+
AND c.location.longitude >= $w AND c.location.longitude <= $e
|
|
657
|
+
RETURN c.name, c.location.latitude AS lat, c.location.longitude AS lon
|
|
658
|
+
ORDER BY lat
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
#### Explanation
|
|
662
|
+
|
|
663
|
+
Use `geo.within_bbox()` for same-SRID bounding boxes. Add a POINT
|
|
664
|
+
index for hot location filters, and keep the component-level `>=` /
|
|
665
|
+
`<=` form only when you need custom fallback logic.
|
|
666
|
+
|
|
667
|
+
#### Variations
|
|
668
|
+
|
|
669
|
+
- Combine with category filter:
|
|
670
|
+
`WHERE c.country = $country AND …`.
|
|
671
|
+
- Return area-approximated stats with
|
|
672
|
+
`count(*)` grouped by rounded coordinates — see
|
|
673
|
+
[Cluster by rounded coordinates](./data-types/spatial.md#cluster-by-rounded-coordinates).
|
|
674
|
+
|
|
675
|
+
#### Related concepts
|
|
676
|
+
|
|
677
|
+
- [Spatial point components](./functions/spatial.md#component-access)
|
|
678
|
+
- [WHERE — arithmetic and comparison](./queries/where.md#comparison)
|
|
679
|
+
|
|
680
|
+
---
|
|
681
|
+
|
|
682
|
+
### Recipe: Closest-per-category
|
|
683
|
+
|
|
684
|
+
#### Problem
|
|
685
|
+
|
|
686
|
+
"Nearest shop of each category to `$here`."
|
|
687
|
+
|
|
688
|
+
#### Assumed data model
|
|
689
|
+
|
|
690
|
+
- `:Shop {category, location}` — WGS-84 2D
|
|
691
|
+
|
|
692
|
+
#### Query
|
|
693
|
+
|
|
694
|
+
```cypher
|
|
695
|
+
MATCH (s:Shop)
|
|
696
|
+
WITH s.category AS category, s, geo.distance(s.location, $here) AS metres
|
|
697
|
+
ORDER BY metres ASC
|
|
698
|
+
WITH category, collect({s: s, metres: metres})[0] AS nearest
|
|
699
|
+
RETURN category,
|
|
700
|
+
nearest.s.name AS name,
|
|
701
|
+
nearest.metres AS metres
|
|
702
|
+
ORDER BY metres
|
|
703
|
+
```
|
|
704
|
+
|
|
705
|
+
#### Explanation
|
|
706
|
+
|
|
707
|
+
Order by distance *first*, then `collect` per category. The first
|
|
708
|
+
collected element is the closest. `collect(…)[0]` is the
|
|
709
|
+
group-level "pick one" idiom — LoraDB has no window functions.
|
|
710
|
+
|
|
711
|
+
#### Variations
|
|
712
|
+
|
|
713
|
+
- Pick the *farthest* in each category: sort `DESC`.
|
|
714
|
+
- Top-3 per category: `collect(…)[..3]` and then `UNWIND` to one
|
|
715
|
+
row per shop.
|
|
716
|
+
|
|
717
|
+
#### Related concepts
|
|
718
|
+
|
|
719
|
+
- [Top contributor per group](./queries/aggregation.md#top-contributor-per-group-pipeline-trick)
|
|
720
|
+
- [collect → slice](./functions/aggregation.md#collect--slice-for-top-n)
|
|
721
|
+
|
|
722
|
+
---
|
|
723
|
+
|
|
724
|
+
### Recipe: Join on proximity
|
|
725
|
+
|
|
726
|
+
#### Problem
|
|
727
|
+
|
|
728
|
+
"Find all pairs of sensors within 500 metres of each other."
|
|
729
|
+
|
|
730
|
+
#### Assumed data model
|
|
731
|
+
|
|
732
|
+
- `:Sensor {id, location}` — WGS-84 2D
|
|
733
|
+
|
|
734
|
+
#### Query
|
|
735
|
+
|
|
736
|
+
```cypher
|
|
737
|
+
MATCH (a:Sensor), (b:Sensor)
|
|
738
|
+
WHERE id(a) < id(b)
|
|
739
|
+
AND geo.distance(a.location, b.location) < 500
|
|
740
|
+
RETURN a.id, b.id, geo.distance(a.location, b.location) AS metres
|
|
741
|
+
ORDER BY metres
|
|
742
|
+
```
|
|
743
|
+
|
|
744
|
+
#### Explanation
|
|
745
|
+
|
|
746
|
+
The Cartesian join between sensors is expensive — use a label scope
|
|
747
|
+
to keep it tight. The `id(a) < id(b)` predicate removes symmetric
|
|
748
|
+
pair duplicates.
|
|
749
|
+
|
|
750
|
+
#### Variations
|
|
751
|
+
|
|
752
|
+
- Constrain by network / region first (`WHERE a.region = b.region`)
|
|
753
|
+
to shrink the cartesian product dramatically.
|
|
754
|
+
- Store a Cartesian point instead for small domains (floor plans,
|
|
755
|
+
game maps) — distance is then an `O(1)` square root.
|
|
756
|
+
|
|
757
|
+
#### Related concepts
|
|
758
|
+
|
|
759
|
+
- [Cartesian products in MATCH](./queries/match.md#multiple-patterns-cross-product)
|
|
760
|
+
- [Performance notes](./queries/paths.md#performance)
|
|
761
|
+
|
|
762
|
+
---
|
|
763
|
+
|
|
764
|
+
## Vector-retrieval patterns
|
|
765
|
+
|
|
766
|
+
### Recipe: Top-k by similarity
|
|
767
|
+
|
|
768
|
+
#### Problem
|
|
769
|
+
|
|
770
|
+
"Return the ten documents most similar to `$query`, exhaustive scan."
|
|
771
|
+
|
|
772
|
+
#### Assumed data model
|
|
773
|
+
|
|
774
|
+
- `:Doc {id, title, embedding}` — `embedding` is a `VECTOR<FLOAT32>`
|
|
775
|
+
of fixed dimension (e.g. 384 for a small sentence-transformer).
|
|
776
|
+
|
|
777
|
+
#### Query
|
|
778
|
+
|
|
779
|
+
```cypher
|
|
780
|
+
MATCH (d:Doc)
|
|
781
|
+
RETURN d.id AS id, d.title AS title
|
|
782
|
+
ORDER BY vector.similarity(d.embedding, $query) DESC
|
|
783
|
+
LIMIT 10
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
Pass `$query` either as a tagged vector (`[...]::VECTOR<FLOAT32>(384)`
|
|
787
|
+
on the host) or as a plain numeric list — both are accepted by the
|
|
788
|
+
similarity function. See
|
|
789
|
+
[Vectors → Passing vectors as parameters](./data-types/vectors.md#passing-vectors-as-parameters).
|
|
790
|
+
|
|
791
|
+
#### Explanation
|
|
792
|
+
|
|
793
|
+
`CREATE VECTOR INDEX` and the `db.index.vector.*` procedures are
|
|
794
|
+
available, but the current implementation still scores linearly within
|
|
795
|
+
the indexed label/type scope. Keep `MATCH` as narrow as possible
|
|
796
|
+
(label, property filter) to shrink the candidate set before similarity
|
|
797
|
+
runs, or use the vector index procedures when the indexed scope matches
|
|
798
|
+
your query shape.
|
|
799
|
+
|
|
800
|
+
#### Variations
|
|
801
|
+
|
|
802
|
+
- **Score in a `WITH` stage** if the score is reused downstream:
|
|
803
|
+
`WITH d, vector.similarity(d.embedding, $query) AS score`.
|
|
804
|
+
- **Swap the metric** for Euclidean-bounded similarity
|
|
805
|
+
(`vector.similarity(d.embedding, $query, 'euclidean')`) or a signed
|
|
806
|
+
distance (`vector.distance(d.embedding, $query, EUCLIDEAN)`, then
|
|
807
|
+
`ORDER BY … ASC`).
|
|
808
|
+
|
|
809
|
+
#### Related concepts
|
|
810
|
+
|
|
811
|
+
- [Vectors](./data-types/vectors.md)
|
|
812
|
+
- [Limitations → Vectors](./limitations.md#vectors)
|
|
813
|
+
|
|
814
|
+
---
|
|
815
|
+
|
|
816
|
+
### Recipe: Graph-filtered retrieval
|
|
817
|
+
|
|
818
|
+
#### Problem
|
|
819
|
+
|
|
820
|
+
"Return the five documents most similar to `$query`, but only those
|
|
821
|
+
that mention an entity of a given type — and include the matched
|
|
822
|
+
entity names in the result."
|
|
823
|
+
|
|
824
|
+
#### Assumed data model
|
|
825
|
+
|
|
826
|
+
- `:Doc {id, title, embedding}` with a `VECTOR` embedding.
|
|
827
|
+
- `(:Doc)-[:MENTIONS]->(:Entity {name, type})`.
|
|
828
|
+
|
|
829
|
+
#### Query
|
|
830
|
+
|
|
831
|
+
```cypher
|
|
832
|
+
MATCH (d:Doc)
|
|
833
|
+
WITH d, vector.similarity(d.embedding, $query) AS score
|
|
834
|
+
MATCH (d)-[:MENTIONS]->(e:Entity)
|
|
835
|
+
WHERE e.type = $entity_type
|
|
836
|
+
RETURN d.id, d.title, score, collect(e.name) AS entities
|
|
837
|
+
ORDER BY score DESC
|
|
838
|
+
LIMIT 5
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
#### Explanation
|
|
842
|
+
|
|
843
|
+
Similarity supplies candidates; the graph explains and constrains
|
|
844
|
+
them. The score is captured once in the first `WITH`, then the
|
|
845
|
+
pipeline walks `MENTIONS` edges for filtering and returns the entity
|
|
846
|
+
list alongside the ranking. This is the shape that motivated putting
|
|
847
|
+
`VECTOR` next to the graph.
|
|
848
|
+
|
|
849
|
+
#### Variations
|
|
850
|
+
|
|
851
|
+
- **Filter before scoring** if the entity constraint is selective —
|
|
852
|
+
move the `MATCH (d)-[:MENTIONS]->(e:Entity {type: $entity_type})`
|
|
853
|
+
above the similarity `WITH` so similarity only scores documents that
|
|
854
|
+
already passed the entity filter.
|
|
855
|
+
- **Rerank by recency** as a tie-breaker:
|
|
856
|
+
`ORDER BY score DESC, d.updated_at DESC`.
|
|
857
|
+
|
|
858
|
+
#### Related concepts
|
|
859
|
+
|
|
860
|
+
- [Vectors → Exhaustive kNN](./data-types/vectors.md#exhaustive-knn)
|
|
861
|
+
- [Queries → Parameters](./queries/parameters.md#semantic-retrieval-with-a-vector-parameter)
|
|
862
|
+
|
|
863
|
+
---
|
|
864
|
+
|
|
865
|
+
## Backup and restore
|
|
866
|
+
|
|
867
|
+
LoraDB's snapshot API lets you persist the full graph to a single
|
|
868
|
+
file and restore it later. It's a point-in-time dump — atomic on
|
|
869
|
+
rename and still useful when you also enable WAL-backed recovery.
|
|
870
|
+
These recipes cover the common snapshot and checkpoint shapes.
|
|
871
|
+
|
|
872
|
+
### Recipe: Periodic snapshot from host code
|
|
873
|
+
|
|
874
|
+
#### Problem
|
|
875
|
+
|
|
876
|
+
"Persist the live graph every N minutes from the same process that
|
|
877
|
+
owns the `Database` handle."
|
|
878
|
+
|
|
879
|
+
#### Assumed setup
|
|
880
|
+
|
|
881
|
+
- Any binding with a `save_snapshot` / `saveSnapshot` method (Rust,
|
|
882
|
+
Python, Node, WASM, Go, Ruby) — see the
|
|
883
|
+
[language-specific quickstarts](./getting-started/installation.md) or
|
|
884
|
+
the canonical [Snapshots guide](./snapshot.md).
|
|
885
|
+
- A writable target path on a local disk.
|
|
886
|
+
|
|
887
|
+
#### Code (Rust)
|
|
888
|
+
|
|
889
|
+
```rust
|
|
890
|
+
use std::time::Duration;
|
|
891
|
+
use std::sync::Arc;
|
|
892
|
+
use lora_database::Database;
|
|
893
|
+
|
|
894
|
+
fn snapshot_loop(db: Arc<Database>, path: &'static str) {
|
|
895
|
+
std::thread::spawn(move || loop {
|
|
896
|
+
std::thread::sleep(Duration::from_secs(300));
|
|
897
|
+
match db.save_snapshot_to(path) {
|
|
898
|
+
Ok(meta) => tracing::info!(
|
|
899
|
+
nodes = meta.node_count,
|
|
900
|
+
rels = meta.relationship_count,
|
|
901
|
+
"snapshot saved"
|
|
902
|
+
),
|
|
903
|
+
Err(e) => tracing::error!(error = %e, "snapshot failed"),
|
|
904
|
+
}
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
```
|
|
908
|
+
|
|
909
|
+
#### Explanation
|
|
910
|
+
|
|
911
|
+
- `save_snapshot_to` writes to `<path>.tmp`, `fsync`s, and renames
|
|
912
|
+
over the target — a crashed save never leaves a half-written file
|
|
913
|
+
at `<path>`.
|
|
914
|
+
- The call encodes the current graph snapshot (`O(n + r)` in nodes and
|
|
915
|
+
relationships) and writes it atomically. Pick an interval larger than the
|
|
916
|
+
measured save wall-time so successive saves don't stack.
|
|
917
|
+
- You can safely overwrite the same path on every tick. For
|
|
918
|
+
versioned backups, rotate the filename (`graph-2026-04-24.bin`)
|
|
919
|
+
and garbage-collect outside the process.
|
|
920
|
+
|
|
921
|
+
#### Variations
|
|
922
|
+
|
|
923
|
+
- **Rotating filenames.** Append a date stamp and prune on a cron.
|
|
924
|
+
- **HTTP from a cron job.** If the server runs with
|
|
925
|
+
`--snapshot-path`, call `POST /admin/snapshot/save` from an
|
|
926
|
+
external cron instead of a thread inside the process. See
|
|
927
|
+
[HTTP API → Admin endpoints](https://loradb.com/docs/api/http#admin-endpoints-opt-in).
|
|
928
|
+
- **Python / Node / WASM / Go / Ruby.** Same shape — see each
|
|
929
|
+
quickstart's _Persisting your graph_ section:
|
|
930
|
+
[Rust](https://loradb.com/docs/getting-started/rust#persisting-your-graph),
|
|
931
|
+
[Python](https://loradb.com/docs/getting-started/python#persisting-your-graph),
|
|
932
|
+
[Node](./getting-started/node.md#persisting-your-graph),
|
|
933
|
+
[WASM](https://loradb.com/docs/getting-started/wasm#persisting-your-graph),
|
|
934
|
+
[Go](https://loradb.com/docs/getting-started/go#persisting-your-graph),
|
|
935
|
+
[Ruby](https://loradb.com/docs/getting-started/ruby#persisting-your-graph).
|
|
936
|
+
|
|
937
|
+
### Recipe: Boot from snapshot, save on shutdown (server setup)
|
|
938
|
+
|
|
939
|
+
#### Problem
|
|
940
|
+
|
|
941
|
+
"Self-hosted `lora-server` should load state at start-up and
|
|
942
|
+
persist it on graceful shutdown."
|
|
943
|
+
|
|
944
|
+
#### Assumed setup
|
|
945
|
+
|
|
946
|
+
- A host running `lora-server` as a long-lived process (systemd, Docker,
|
|
947
|
+
plain `nohup`, …).
|
|
948
|
+
- A writable path for the snapshot file.
|
|
949
|
+
|
|
950
|
+
#### Configuration
|
|
951
|
+
|
|
952
|
+
```bash
|
|
953
|
+
# start-up — restore from, and default-save to, the same file
|
|
954
|
+
lora-server \
|
|
955
|
+
--host 127.0.0.1 --port 4747 \
|
|
956
|
+
--snapshot-path /var/lib/lora/db.bin \
|
|
957
|
+
--restore-from /var/lib/lora/db.bin
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
`--restore-from` at boot: missing file is fine (empty graph, logged);
|
|
961
|
+
malformed file is fatal.
|
|
962
|
+
|
|
963
|
+
#### Save on shutdown (systemd sketch)
|
|
964
|
+
|
|
965
|
+
```ini
|
|
966
|
+
# /etc/systemd/system/lora-server.service
|
|
967
|
+
[Service]
|
|
968
|
+
ExecStart=/usr/local/bin/lora-server \
|
|
969
|
+
--host 127.0.0.1 --port 4747 \
|
|
970
|
+
--snapshot-path /var/lib/lora/db.bin \
|
|
971
|
+
--restore-from /var/lib/lora/db.bin
|
|
972
|
+
ExecStop=/usr/bin/curl -sX POST http://127.0.0.1:4747/admin/snapshot/save
|
|
973
|
+
TimeoutStopSec=30
|
|
974
|
+
```
|
|
975
|
+
|
|
976
|
+
The `ExecStop` call saves the current state before the process is
|
|
977
|
+
killed. `TimeoutStopSec` needs to comfortably cover your measured
|
|
978
|
+
save duration.
|
|
979
|
+
|
|
980
|
+
#### Explanation
|
|
981
|
+
|
|
982
|
+
- The admin endpoints are opt-in — they're mounted **only** because
|
|
983
|
+
`--snapshot-path` is set. On any other host they return `404`.
|
|
984
|
+
- The admin surface has **no authentication**, so the bind address
|
|
985
|
+
must be privileged (here: `127.0.0.1` only). See
|
|
986
|
+
[HTTP API → Admin endpoints (opt-in)](https://loradb.com/docs/api/http#admin-endpoints-opt-in)
|
|
987
|
+
for the security warning.
|
|
988
|
+
- The save runs as the server UID, which must have write access to
|
|
989
|
+
the target path and its parent directory.
|
|
990
|
+
|
|
991
|
+
#### Variations
|
|
992
|
+
|
|
993
|
+
- **Scheduled cron-driven saves.** Combine the boot-from-snapshot
|
|
994
|
+
setup above with a systemd `.timer` unit or an ordinary cron that
|
|
995
|
+
curls `POST /admin/snapshot/save` every N minutes. The endpoint
|
|
996
|
+
returns a `SnapshotMeta` you can log for observability.
|
|
997
|
+
- **Immutable seed + writable runtime.** Pass `--restore-from
|
|
998
|
+
/var/lib/lora/seed.bin` and `--snapshot-path /var/lib/lora/runtime.bin`
|
|
999
|
+
to boot from a shared seed and save to a host-local file.
|
|
1000
|
+
|
|
1001
|
+
### Recipe: WAL-backed server with explicit checkpoints
|
|
1002
|
+
|
|
1003
|
+
#### Problem
|
|
1004
|
+
|
|
1005
|
+
"Recover committed writes after a crash, but keep replay time bounded
|
|
1006
|
+
with operator-driven checkpoints."
|
|
1007
|
+
|
|
1008
|
+
#### Assumed setup
|
|
1009
|
+
|
|
1010
|
+
- `lora-server` owns a writable WAL directory.
|
|
1011
|
+
- A writable snapshot path where checkpoints should land.
|
|
1012
|
+
- Admin endpoints are reachable only through trusted local transport
|
|
1013
|
+
or authenticated ingress.
|
|
1014
|
+
|
|
1015
|
+
#### Configuration
|
|
1016
|
+
|
|
1017
|
+
```bash
|
|
1018
|
+
lora-server \
|
|
1019
|
+
--host 127.0.0.1 --port 4747 \
|
|
1020
|
+
--wal-dir /var/lib/lora/wal \
|
|
1021
|
+
--snapshot-path /var/lib/lora/db.bin \
|
|
1022
|
+
--restore-from /var/lib/lora/db.bin
|
|
1023
|
+
```
|
|
1024
|
+
|
|
1025
|
+
#### Checkpoint cadence
|
|
1026
|
+
|
|
1027
|
+
```bash
|
|
1028
|
+
# Inspect the WAL before deciding whether to checkpoint.
|
|
1029
|
+
curl -sX POST http://127.0.0.1:4747/admin/wal/status
|
|
1030
|
+
|
|
1031
|
+
# Write a checkpoint snapshot to --snapshot-path and truncate safe history.
|
|
1032
|
+
curl -sX POST http://127.0.0.1:4747/admin/checkpoint
|
|
1033
|
+
```
|
|
1034
|
+
|
|
1035
|
+
If you run WAL-only without `--snapshot-path`, pass the checkpoint
|
|
1036
|
+
target explicitly:
|
|
1037
|
+
|
|
1038
|
+
```bash
|
|
1039
|
+
curl -sX POST http://127.0.0.1:4747/admin/checkpoint \
|
|
1040
|
+
-H 'content-type: application/json' \
|
|
1041
|
+
-d '{"path":"/var/lib/lora/checkpoint.bin"}'
|
|
1042
|
+
```
|
|
1043
|
+
|
|
1044
|
+
#### Explanation
|
|
1045
|
+
|
|
1046
|
+
- Normal writes are logged to `/var/lib/lora/wal`. Restarting with the
|
|
1047
|
+
same `--wal-dir` replays committed records automatically.
|
|
1048
|
+
- `POST /admin/checkpoint` writes a snapshot stamped with `walLsn`,
|
|
1049
|
+
appends a checkpoint marker, then drops sealed WAL segments that are
|
|
1050
|
+
safe to remove.
|
|
1051
|
+
- `--restore-from` and `--snapshot-path` are independent. They can be
|
|
1052
|
+
the same file for a simple single-host setup, or different files for
|
|
1053
|
+
an immutable seed plus writable runtime checkpoint.
|
|
1054
|
+
- There is no wall-clock checkpoint scheduler. Trigger the endpoint
|
|
1055
|
+
from a systemd timer, cron, deployment hook, or host process after
|
|
1056
|
+
you measure acceptable replay time. Embedded raw-WAL helpers can also
|
|
1057
|
+
write managed snapshots after N committed transactions; see
|
|
1058
|
+
[WAL and checkpoints](./wal.md).
|
|
1059
|
+
|
|
1060
|
+
See the canonical [Snapshots guide](./snapshot.md) for the file format
|
|
1061
|
+
and every binding's save / load API, and
|
|
1062
|
+
[WAL and checkpoints](./wal.md) for recovery, sync modes, and admin
|
|
1063
|
+
semantics.
|
|
1064
|
+
|
|
1065
|
+
---
|
|
1066
|
+
|
|
1067
|
+
## See also
|
|
1068
|
+
|
|
1069
|
+
- [**Queries → Examples**](./queries/examples.md) — copy-paste recipes
|
|
1070
|
+
grouped by clause.
|
|
1071
|
+
- [**Queries → Aggregation**](./queries/aggregation.md) — clause-level
|
|
1072
|
+
grouping, HAVING, percentiles.
|
|
1073
|
+
- [**HTTP server → Snapshots, WAL, and restore**](https://loradb.com/docs/getting-started/server#snapshots-wal-and-restore)
|
|
1074
|
+
— flag reference for the admin endpoints.
|
|
1075
|
+
- [**HTTP API → Admin endpoints (opt-in)**](https://loradb.com/docs/api/http#admin-endpoints-opt-in)
|
|
1076
|
+
— full wire reference.
|
|
1077
|
+
- [**Tutorial**](./getting-started/tutorial.md) — guided from-zero walkthrough.
|
|
1078
|
+
- [**Troubleshooting**](./troubleshooting.md) — what to do when a
|
|
1079
|
+
recipe returns fewer rows than you expected.
|
|
1080
|
+
- [**Concepts → Modelling checklist**](./concepts/graph-model.md#modelling-checklist)
|
|
1081
|
+
— how to decide the shape of a new domain.
|