uni-db 1.1.0

Embedded graph database with OpenCypher queries, vector search, and columnar storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// Integration tests for Rust notebook examples
// These tests mirror the Jupyter notebook examples to verify they work correctly.

use std::collections::HashMap;
use tempfile::tempdir;
use uni_db::unival;
use uni_db::{DataType, IndexType, ScalarType, Uni, VectorAlgo, VectorIndexCfg, VectorMetric};

// ============================================================================
// Supply Chain Example
// ============================================================================
#[tokio::test]
async fn test_supply_chain() -> anyhow::Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().to_str().unwrap();

    let db = Uni::open(db_path).build().await.unwrap();

    // Schema
    db.schema()
        .label("Part")
        .property("sku", DataType::String)
        .property("cost", DataType::Float64)
        .index("sku", IndexType::Scalar(ScalarType::Hash))
        .label("Supplier")
        .label("Product")
        .property("name", DataType::String)
        .property("price", DataType::Float64)
        .edge_type("ASSEMBLED_FROM", &["Product", "Part"], &["Part"])
        .edge_type("SUPPLIED_BY", &["Part"], &["Supplier"])
        .apply()
        .await
        .unwrap();

    // Insert Parts
    let part_props: Vec<uni_db::common::Properties> = vec![
        HashMap::from([
            ("sku".to_string(), unival!("RES-10K")),
            ("cost".to_string(), unival!(0.05)),
        ]),
        HashMap::from([
            ("sku".to_string(), unival!("MB-X1")),
            ("cost".to_string(), unival!(50.0)),
        ]),
        HashMap::from([
            ("sku".to_string(), unival!("SCR-OLED")),
            ("cost".to_string(), unival!(30.0)),
        ]),
    ];

    let tx = db.session().tx().await.unwrap();
    let part_vids = tx.bulk_insert_vertices("Part", part_props).await.unwrap();
    let (p1, p2, p3) = (part_vids[0], part_vids[1], part_vids[2]);

    // Insert Product
    let prod_props: Vec<uni_db::common::Properties> = vec![HashMap::from([
        ("name".to_string(), unival!("Smartphone X")),
        ("price".to_string(), unival!(500.0)),
    ])];

    let phone_vids = tx
        .bulk_insert_vertices("Product", prod_props)
        .await
        .unwrap();
    let phone = phone_vids[0];

    // Create assembly relationships
    tx.bulk_insert_edges(
        "ASSEMBLED_FROM",
        vec![
            (phone, p2, HashMap::new()), // phone <- MB-X1
            (phone, p3, HashMap::new()), // phone <- SCR-OLED
            (p2, p1, HashMap::new()),    // MB-X1 <- RES-10K
        ],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    db.flush().await.unwrap();

    // Warm up adjacency cache
    db.session()
        .query("MATCH (a:Part)-[:ASSEMBLED_FROM]->(b:Part) RETURN a.sku")
        .await
        .unwrap();

    // BOM explosion query
    let query = r#"
        MATCH (defective:Part {sku: 'RES-10K'})
        MATCH (product:Product)-[:ASSEMBLED_FROM*1..5]->(defective)
        RETURN product.name as name, product.price as price
    "#;

    let results = db.session().query(query).await.unwrap();
    println!("Products affected: {:?}", results.rows());
    assert!(!results.is_empty(), "Should find affected products");

    // Cost rollup
    let query_cost = r#"
        MATCH (p:Product {name: 'Smartphone X'})
        MATCH (p)-[:ASSEMBLED_FROM*1..5]->(part:Part)
        RETURN SUM(part.cost) AS total_bom_cost
    "#;

    let results = db.session().query(query_cost).await.unwrap();
    println!("Total BOM Cost: {:?}", results.rows()[0]);

    Ok(())
}

// ============================================================================
// Recommendation Example
// ============================================================================
#[tokio::test]
async fn test_recommendation() -> anyhow::Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().to_str().unwrap();

    let db = Uni::open(db_path).build().await.unwrap();

    // Schema
    db.schema()
        .label("User")
        .property("name", DataType::String)
        .label("Product")
        .property("name", DataType::String)
        .property("price", DataType::Float64)
        .property("embedding", DataType::Vector { dimensions: 4 })
        .index(
            "embedding",
            IndexType::Vector(VectorIndexCfg {
                algorithm: VectorAlgo::Flat,
                metric: VectorMetric::Cosine,
                embedding: None,
            }),
        )
        .edge_type("VIEWED", &["User"], &["Product"])
        .edge_type("PURCHASED", &["User"], &["Product"])
        .apply()
        .await
        .unwrap();

    // Product embeddings
    let p1_vec = vec![1.0, 0.0, 0.0, 0.0]; // Running Shoes
    let p2_vec = vec![0.9, 0.1, 0.0, 0.0]; // Socks (similar)
    let p3_vec = vec![0.0, 1.0, 0.0, 0.0]; // Shampoo (different)

    let products: Vec<uni_db::common::Properties> = vec![
        HashMap::from([
            ("name".to_string(), unival!("Running Shoes")),
            ("price".to_string(), unival!(100.0)),
            ("embedding".to_string(), unival!(p1_vec)),
        ]),
        HashMap::from([
            ("name".to_string(), unival!("Socks")),
            ("price".to_string(), unival!(10.0)),
            ("embedding".to_string(), unival!(p2_vec)),
        ]),
        HashMap::from([
            ("name".to_string(), unival!("Shampoo")),
            ("price".to_string(), unival!(5.0)),
            ("embedding".to_string(), unival!(p3_vec)),
        ]),
    ];

    let tx = db.session().tx().await.unwrap();
    let prod_vids = tx.bulk_insert_vertices("Product", products).await.unwrap();
    let (p1, p2, p3) = (prod_vids[0], prod_vids[1], prod_vids[2]);

    // Users
    let users: Vec<uni_db::common::Properties> = vec![
        HashMap::from([("name".to_string(), unival!("Alice"))]),
        HashMap::from([("name".to_string(), unival!("Bob"))]),
        HashMap::from([("name".to_string(), unival!("Charlie"))]),
    ];

    let user_vids = tx.bulk_insert_vertices("User", users).await.unwrap();
    let (u1, u2, u3) = (user_vids[0], user_vids[1], user_vids[2]);

    // Purchase history
    tx.bulk_insert_edges(
        "PURCHASED",
        vec![
            (u1, p1, HashMap::new()),
            (u2, p1, HashMap::new()),
            (u3, p1, HashMap::new()),
        ],
    )
    .await
    .unwrap();

    // View history
    tx.bulk_insert_edges(
        "VIEWED",
        vec![(u1, p2, HashMap::new()), (u1, p3, HashMap::new())],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    db.flush().await.unwrap();

    // Collaborative filtering
    let query = r#"
        MATCH (u1:User {name: 'Alice'})-[:PURCHASED]->(p:Product)<-[:PURCHASED]-(other:User)
        WHERE other._vid <> u1._vid
        RETURN count(DISTINCT other) as count
    "#;

    let results = db.session().query(query).await.unwrap();
    println!(
        "Users with similar purchase history: {:?}",
        results.rows()[0]
    );

    Ok(())
}

// ============================================================================
// RAG Example
// ============================================================================
#[tokio::test]
async fn test_rag() -> anyhow::Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().to_str().unwrap();

    let db = Uni::open(db_path).build().await.unwrap();

    // Schema
    db.schema()
        .label("Chunk")
        .property("text", DataType::String)
        .property("embedding", DataType::Vector { dimensions: 4 })
        .index(
            "embedding",
            IndexType::Vector(VectorIndexCfg {
                algorithm: VectorAlgo::Flat,
                metric: VectorMetric::Cosine,
                embedding: None,
            }),
        )
        .label("Entity")
        .property("name", DataType::String)
        .property("type", DataType::String)
        .edge_type("MENTIONS", &["Chunk"], &["Entity"])
        .apply()
        .await
        .unwrap();

    // Chunk embeddings
    let c1_vec = vec![1.0, 0.0, 0.0, 0.0];
    let c2_vec = vec![0.9, 0.1, 0.0, 0.0];

    let chunks: Vec<uni_db::common::Properties> = vec![
        HashMap::from([
            (
                "text".to_string(),
                unival!("Function verify() checks signatures."),
            ),
            ("embedding".to_string(), unival!(c1_vec)),
        ]),
        HashMap::from([
            ("text".to_string(), unival!("Other text about verify.")),
            ("embedding".to_string(), unival!(c2_vec)),
        ]),
    ];

    let tx = db.session().tx().await.unwrap();
    let chunk_vids = tx.bulk_insert_vertices("Chunk", chunks).await.unwrap();
    let (c1, c2) = (chunk_vids[0], chunk_vids[1]);

    // Entities
    let entities: Vec<uni_db::common::Properties> = vec![HashMap::from([
        ("name".to_string(), unival!("verify")),
        ("type".to_string(), unival!("function")),
    ])];

    let entity_vids = tx.bulk_insert_vertices("Entity", entities).await.unwrap();
    let e1 = entity_vids[0];

    // Link chunks to entities
    tx.bulk_insert_edges(
        "MENTIONS",
        vec![(c1, e1, HashMap::new()), (c2, e1, HashMap::new())],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    db.flush().await.unwrap();

    // Hybrid retrieval
    let query = format!(
        r#"
        MATCH (c:Chunk)-[:MENTIONS]->(e:Entity)<-[:MENTIONS]-(related:Chunk)
        WHERE c._vid = {} AND related._vid <> c._vid
        RETURN related.text as text
    "#,
        c1.as_u64()
    );

    let results = db.session().query(&query).await.unwrap();
    println!("Related chunks: {:?}", results.rows());
    assert!(!results.is_empty(), "Should find related chunks");

    Ok(())
}

// ============================================================================
// Fraud Detection Example
// ============================================================================
#[tokio::test]
async fn test_fraud_detection() -> anyhow::Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().to_str().unwrap();

    let db = Uni::open(db_path).build().await.unwrap();

    // Schema
    db.schema()
        .label("User")
        .property_nullable("risk_score", DataType::Float32)
        .label("Device")
        .edge_type("SENT_MONEY", &["User"], &["User"])
        .property("amount", DataType::Float64)
        .edge_type("USED_DEVICE", &["User"], &["Device"])
        .apply()
        .await
        .unwrap();

    // Users with risk scores
    let users: Vec<uni_db::common::Properties> = vec![
        HashMap::from([("risk_score".to_string(), unival!(0.1))]), // A
        HashMap::from([("risk_score".to_string(), unival!(0.2))]), // B
        HashMap::from([("risk_score".to_string(), unival!(0.3))]), // C
        HashMap::from([("risk_score".to_string(), unival!(0.9))]), // D (Fraudster)
    ];

    let tx = db.session().tx().await.unwrap();
    let user_vids = tx.bulk_insert_vertices("User", users).await.unwrap();
    let (ua, ub, uc, ud) = (user_vids[0], user_vids[1], user_vids[2], user_vids[3]);

    // Device
    let devices = vec![HashMap::new()];
    let device_vids = tx.bulk_insert_vertices("Device", devices).await.unwrap();
    let d1 = device_vids[0];

    // Money transfer cycle: A -> B -> C -> A
    tx.bulk_insert_edges(
        "SENT_MONEY",
        vec![
            (
                ua,
                ub,
                HashMap::from([("amount".to_string(), unival!(5000.0))]),
            ),
            (
                ub,
                uc,
                HashMap::from([("amount".to_string(), unival!(5000.0))]),
            ),
            (
                uc,
                ua,
                HashMap::from([("amount".to_string(), unival!(5000.0))]),
            ),
        ],
    )
    .await
    .unwrap();

    // Shared device
    tx.bulk_insert_edges(
        "USED_DEVICE",
        vec![(ua, d1, HashMap::new()), (ud, d1, HashMap::new())],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    db.flush().await.unwrap();

    // Cycle detection
    let query_cycle = r#"
        MATCH (a:User)-[:SENT_MONEY]->(b:User)-[:SENT_MONEY]->(c:User)-[:SENT_MONEY]->(a)
        RETURN count(*) as count
    "#;

    let results = db.session().query(query_cycle).await.unwrap();
    println!("Cycles detected: {:?}", results.rows()[0]);

    // Shared device analysis
    let query_shared = r#"
        MATCH (u:User)-[:USED_DEVICE]->(d:Device)<-[:USED_DEVICE]-(fraudster:User)
        WHERE fraudster.risk_score > 0.8 AND u._vid <> fraudster._vid
        RETURN u._vid as uid
    "#;

    let results = db.session().query(query_shared).await.unwrap();
    println!(
        "User sharing device with fraudster: {:?}",
        results.rows()[0]
    );
    assert!(!results.is_empty(), "Should find user sharing device");

    Ok(())
}

// ============================================================================
// Sales Analytics Example
// ============================================================================
#[tokio::test]
async fn test_sales_analytics() -> anyhow::Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().to_str().unwrap();

    let db = Uni::open(db_path).build().await.unwrap();

    // Schema
    db.schema()
        .label("Region")
        .property("name", DataType::String)
        .label("ORDER")
        .property("amount", DataType::Float64)
        .edge_type("SHIPPED_TO", &["ORDER"], &["Region"])
        .apply()
        .await
        .unwrap();

    // Create region
    let regions: Vec<uni_db::common::Properties> =
        vec![HashMap::from([("name".to_string(), unival!("North"))])];

    let tx = db.session().tx().await.unwrap();
    let region_vids = tx.bulk_insert_vertices("Region", regions).await.unwrap();
    let north = region_vids[0];

    // Create 100 orders
    let orders: Vec<uni_db::common::Properties> = (0..100)
        .map(|i| HashMap::from([("amount".to_string(), unival!(10.0 * (i + 1) as f64))]))
        .collect();

    let order_vids = tx.bulk_insert_vertices("ORDER", orders).await.unwrap();

    // Ship all orders to North region
    let edges: Vec<_> = order_vids
        .iter()
        .map(|vid| (*vid, north, HashMap::new()))
        .collect();

    tx.bulk_insert_edges("SHIPPED_TO", edges).await.unwrap();
    tx.commit().await.unwrap();
    db.flush().await.unwrap();

    // Analytical query
    let query = r#"
        MATCH (r:Region {name: 'North'})<-[:SHIPPED_TO]-(o:Order)
        RETURN SUM(o.amount) as total
    "#;

    let results = db.session().query(query).await.unwrap();
    println!("Total Sales for North Region: {:?}", results.rows()[0]);

    // Verify: 10 * (1 + 2 + ... + 100) = 10 * 5050 = 50500
    // The result should contain 50500.0

    Ok(())
}