triviumdb 0.4.91

A high-performance memory-mmap hybrid search engine built for AI, combining dense vector, sparse text, graph relations, and JSON metadata.
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
#[cfg(feature = "nodejs")]
pub mod nodejs {
    use crate::database::Database as GenericDatabase;
    use crate::filter::Filter;
    use napi_derive::napi;

    // ════════ 后端枚举:封装三种泛型特化 ════════

    enum DbBackend {
        F32(GenericDatabase<f32>),
        F16(GenericDatabase<half::f16>),
        U64(GenericDatabase<u64>),
    }

    /// 统一分发宏:对三种后端执行相同的表达式
    macro_rules! dispatch {
        ($self:expr, $db:ident => $expr:expr) => {
            match &$self.inner {
                DbBackend::F32($db) => $expr,
                DbBackend::F16($db) => $expr,
                DbBackend::U64($db) => $expr,
            }
        };
        ($self:expr, mut $db:ident => $expr:expr) => {
            match &mut $self.inner {
                DbBackend::F32($db) => $expr,
                DbBackend::F16($db) => $expr,
                DbBackend::U64($db) => $expr,
            }
        };
    }

    // ════════ JS 侧返回结构体 ════════

    /// 向量检索命中结果
    #[napi(object)]
    pub struct JsSearchHit {
        /// 节点 ID(JS Number,安全范围内的 u64)
        pub id: f64,
        /// 相似度得分
        pub score: f64,
        /// 节点元数据(JSON 对象)
        pub payload: serde_json::Value,
    }

    /// 高级管线专用配置结构
    #[napi(object)]
    pub struct JsSearchConfig {
        pub top_k: Option<u32>,
        pub expand_depth: Option<u32>,
        pub min_score: Option<f64>,
        pub teleport_alpha: Option<f64>,
        pub enable_advanced_pipeline: Option<bool>,
        pub enable_sparse_residual: Option<bool>,
        pub fista_lambda: Option<f64>,
        pub fista_threshold: Option<f64>,
        pub enable_dpp: Option<bool>,
        pub dpp_quality_weight: Option<f64>,
        pub enable_refractory_fatigue: Option<bool>,
        pub enable_text_hybrid_search: Option<bool>,
        pub text_boost: Option<f64>,
        pub bq_candidate_ratio: Option<f64>,
        pub custom_query_text: Option<String>,
    }

    /// 节点关系边
    #[napi(object)]
    pub struct JsEdge {
        pub target_id: f64,
        pub label: String,
        pub weight: f64,
    }

    /// 节点完整视图
    #[napi(object)]
    pub struct JsNodeView {
        pub id: f64,
        pub vector: Vec<f64>,
        pub payload: serde_json::Value,
        pub edges: Vec<JsEdge>,
        pub num_edges: u32,
    }

    // ════════ 辅助:JSON Value → Filter ════════

    fn json_to_filter(val: &serde_json::Value) -> napi::Result<Filter> {
        let obj = val
            .as_object()
            .ok_or_else(|| napi::Error::from_reason("过滤条件必须是 JSON 对象"))?;

        let mut filters = Vec::new();

        for (key, v) in obj {
            if key == "$and" {
                let arr = v
                    .as_array()
                    .ok_or_else(|| napi::Error::from_reason("$and 必须是数组"))?;
                let sub: napi::Result<Vec<Filter>> = arr.iter().map(json_to_filter).collect();
                filters.push(Filter::And(sub?));
                continue;
            }
            if key == "$or" {
                let arr = v
                    .as_array()
                    .ok_or_else(|| napi::Error::from_reason("$or 必须是数组"))?;
                let sub: napi::Result<Vec<Filter>> = arr.iter().map(json_to_filter).collect();
                filters.push(Filter::Or(sub?));
                continue;
            }

            // 运算符字典:{"field": {"$gt": 18}}
            if let Some(op_obj) = v.as_object() {
                for (op, op_val) in op_obj {
                    let f = match op.as_str() {
                        "$eq" => Filter::Eq(key.clone(), op_val.clone()),
                        "$ne" => Filter::Ne(key.clone(), op_val.clone()),
                        "$gt" => Filter::Gt(
                            key.clone(),
                            op_val
                                .as_f64()
                                .ok_or_else(|| napi::Error::from_reason("$gt 需要数字"))?,
                        ),
                        "$gte" => Filter::Gte(
                            key.clone(),
                            op_val
                                .as_f64()
                                .ok_or_else(|| napi::Error::from_reason("$gte 需要数字"))?,
                        ),
                        "$lt" => Filter::Lt(
                            key.clone(),
                            op_val
                                .as_f64()
                                .ok_or_else(|| napi::Error::from_reason("$lt 需要数字"))?,
                        ),
                        "$lte" => Filter::Lte(
                            key.clone(),
                            op_val
                                .as_f64()
                                .ok_or_else(|| napi::Error::from_reason("$lte 需要数字"))?,
                        ),
                        "$in" => {
                            let arr = op_val
                                .as_array()
                                .ok_or_else(|| napi::Error::from_reason("$in 需要数组"))?;
                            Filter::In(key.clone(), arr.clone())
                        }
                        "$exists" => {
                            let b = op_val
                                .as_bool()
                                .ok_or_else(|| napi::Error::from_reason("$exists 需要布尔值"))?;
                            Filter::Exists(key.clone(), b)
                        }
                        "$nin" => {
                            let arr = op_val
                                .as_array()
                                .ok_or_else(|| napi::Error::from_reason("$nin 需要数组"))?;
                            Filter::Nin(key.clone(), arr.clone())
                        }
                        "$size" => {
                            let s = op_val
                                .as_u64()
                                .ok_or_else(|| napi::Error::from_reason("$size 需要非负整数"))?;
                            Filter::Size(key.clone(), s as usize)
                        }
                        "$all" => {
                            let arr = op_val
                                .as_array()
                                .ok_or_else(|| napi::Error::from_reason("$all 需要数组"))?;
                            Filter::All(key.clone(), arr.clone())
                        }
                        "$type" => {
                            let t = op_val
                                .as_str()
                                .ok_or_else(|| napi::Error::from_reason("$type 需要字符串"))?;
                            Filter::TypeMatch(key.clone(), t.to_string())
                        }
                        other => {
                            return Err(napi::Error::from_reason(format!(
                                "不支持的运算符: {}",
                                other
                            )));
                        }
                    };
                    filters.push(f);
                }
            } else {
                // 简写等值:{"field": value}
                filters.push(Filter::Eq(key.clone(), v.clone()));
            }
        }

        match filters.len() {
            0 => Ok(Filter::Eq("none".into(), serde_json::Value::Null)),
            1 => Ok(filters.pop().unwrap()),
            _ => Ok(Filter::And(filters)),
        }
    }

    fn parse_sync_mode(s: &str) -> napi::Result<crate::storage::wal::SyncMode> {
        match s {
            "full" => Ok(crate::storage::wal::SyncMode::Full),
            "normal" => Ok(crate::storage::wal::SyncMode::Normal),
            "off" => Ok(crate::storage::wal::SyncMode::Off),
            other => Err(napi::Error::from_reason(format!(
                "不支持的 sync_mode: {},可选值: full/normal/off",
                other
            ))),
        }
    }

    // ════════ TriviumDB 主类 ════════

    #[napi(js_name = "TriviumDB")]
    pub struct TriviumDB {
        inner: DbBackend,
        dtype: String,
    }

    #[napi]
    impl TriviumDB {
        /// 打开或创建数据库
        ///
        /// ```js
        /// const db = new TriviumDB("data.tdb", 1536, "f32", "normal")
        /// ```
        #[napi(constructor)]
        pub fn new(
            path: String,
            dim: Option<u32>,
            dtype: Option<String>,
            sync_mode: Option<String>,
        ) -> napi::Result<Self> {
            let dim = dim.unwrap_or(1536) as usize;
            let dtype_str = dtype.as_deref().unwrap_or("f32");
            let sm = parse_sync_mode(sync_mode.as_deref().unwrap_or("normal"))?;

            let inner = match dtype_str {
                "f32" => DbBackend::F32(
                    GenericDatabase::<f32>::open_with_sync(&path, dim, sm)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))?,
                ),
                "f16" => DbBackend::F16(
                    GenericDatabase::<half::f16>::open_with_sync(&path, dim, sm)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))?,
                ),
                "u64" => DbBackend::U64(
                    GenericDatabase::<u64>::open_with_sync(&path, dim, sm)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))?,
                ),
                _ => return Err(napi::Error::from_reason("dtype 必须是 f32 / f16 / u64")),
            };
            Ok(Self {
                inner,
                dtype: dtype_str.to_string(),
            })
        }

        // ── CRUD ──

        /// 插入节点,返回新节点 ID
        #[napi]
        pub fn insert(
            &mut self,
            vector: Vec<f64>,
            payload: serde_json::Value,
        ) -> napi::Result<f64> {
            match &mut self.inner {
                DbBackend::F32(db) => {
                    let v: Vec<f32> = vector.iter().map(|&x| x as f32).collect();
                    db.insert(&v, payload)
                        .map(|id| id as f64)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
                DbBackend::F16(db) => {
                    let v: Vec<half::f16> =
                        vector.iter().map(|&x| half::f16::from_f64(x)).collect();
                    db.insert(&v, payload)
                        .map(|id| id as f64)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
                DbBackend::U64(db) => {
                    let v: Vec<u64> = vector.iter().map(|&x| x as u64).collect();
                    db.insert(&v, payload)
                        .map(|id| id as f64)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
            }
        }

        /// 批量插入节点,返回新分配的 ID 列表
        #[napi]
        pub fn batch_insert(
            &mut self,
            vectors: Vec<Vec<f64>>,
            payloads: Vec<serde_json::Value>,
        ) -> napi::Result<Vec<f64>> {
            if vectors.len() != payloads.len() {
                return Err(napi::Error::from_reason("向量列表与负载列表长度不一致"));
            }
            let mut ids = Vec::with_capacity(vectors.len());
            for (v, p) in vectors.into_iter().zip(payloads.into_iter()) {
                let id = self.insert(v, p)?;
                ids.push(id);
            }
            Ok(ids)
        }

        /// 批量插入指定 ID 的节点
        #[napi]
        pub fn batch_insert_with_ids(
            &mut self,
            ids: Vec<f64>,
            vectors: Vec<Vec<f64>>,
            payloads: Vec<serde_json::Value>,
        ) -> napi::Result<()> {
            if ids.len() != vectors.len() || vectors.len() != payloads.len() {
                return Err(napi::Error::from_reason("ID、向量与负载列表长度不一致"));
            }
            for ((id, v), p) in ids
                .into_iter()
                .zip(vectors.into_iter())
                .zip(payloads.into_iter())
            {
                self.insert_with_id(id, v, p)?;
            }
            Ok(())
        }

        /// 带指定 ID 插入节点
        #[napi]
        pub fn insert_with_id(
            &mut self,
            id: f64,
            vector: Vec<f64>,
            payload: serde_json::Value,
        ) -> napi::Result<()> {
            let id = id as u64;
            match &mut self.inner {
                DbBackend::F32(db) => {
                    let v: Vec<f32> = vector.iter().map(|&x| x as f32).collect();
                    db.insert_with_id(id, &v, payload)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
                DbBackend::F16(db) => {
                    let v: Vec<half::f16> =
                        vector.iter().map(|&x| half::f16::from_f64(x)).collect();
                    db.insert_with_id(id, &v, payload)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
                DbBackend::U64(db) => {
                    let v: Vec<u64> = vector.iter().map(|&x| x as u64).collect();
                    db.insert_with_id(id, &v, payload)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
            }
        }

        /// 按 ID 获取节点,不存在时返回 null
        #[napi]
        pub fn get(&self, id: f64) -> Option<JsNodeView> {
            let id = id as u64;
            match &self.inner {
                DbBackend::F32(db) => db.get(id).map(|n| {
                    let num_edges = n.edges.len() as u32;
                    let edges_arr = n.edges.into_iter().map(|e| JsEdge {
                        target_id: e.target_id as f64,
                        label: e.label.clone(),
                        weight: e.weight as f64,
                    }).collect();
                    JsNodeView {
                        id: n.id as f64,
                        vector: n.vector.iter().map(|&x| x as f64).collect(),
                        payload: n.payload,
                        edges: edges_arr,
                        num_edges,
                    }
                }),
                DbBackend::F16(db) => db.get(id).map(|n| {
                    let num_edges = n.edges.len() as u32;
                    let edges_arr = n.edges.into_iter().map(|e| JsEdge {
                        target_id: e.target_id as f64,
                        label: e.label.clone(),
                        weight: e.weight as f64,
                    }).collect();
                    JsNodeView {
                        id: n.id as f64,
                        vector: n.vector.iter().map(|x| x.to_f64()).collect(),
                        payload: n.payload,
                        edges: edges_arr,
                        num_edges,
                    }
                }),
                DbBackend::U64(db) => db.get(id).map(|n| {
                    let num_edges = n.edges.len() as u32;
                    let edges_arr = n.edges.into_iter().map(|e| JsEdge {
                        target_id: e.target_id as f64,
                        label: e.label.clone(),
                        weight: e.weight as f64,
                    }).collect();
                    JsNodeView {
                        id: n.id as f64,
                        vector: n.vector.iter().map(|&x| x as f64).collect(),
                        payload: n.payload,
                        edges: edges_arr,
                        num_edges,
                    }
                }),
            }
        }

        /// 更新节点元数据
        #[napi]
        pub fn update_payload(&mut self, id: f64, payload: serde_json::Value) -> napi::Result<()> {
            dispatch!(self, mut db => db.update_payload(id as u64, payload))
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        /// 更新节点向量
        #[napi]
        pub fn update_vector(&mut self, id: f64, vector: Vec<f64>) -> napi::Result<()> {
            let id = id as u64;
            match &mut self.inner {
                DbBackend::F32(db) => {
                    let v: Vec<f32> = vector.iter().map(|&x| x as f32).collect();
                    db.update_vector(id, &v)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
                DbBackend::F16(db) => {
                    let v: Vec<half::f16> =
                        vector.iter().map(|&x| half::f16::from_f64(x)).collect();
                    db.update_vector(id, &v)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
                DbBackend::U64(db) => {
                    let v: Vec<u64> = vector.iter().map(|&x| x as u64).collect();
                    db.update_vector(id, &v)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))
                }
            }
        }

        /// 删除节点(三层原子联删:向量 + Payload + 所有关联边)
        #[napi]
        pub fn delete(&mut self, id: f64) -> napi::Result<()> {
            dispatch!(self, mut db => db.delete(id as u64))
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        // ── 图谱操作 ──

        /// 建立有向带权边
        #[napi]
        pub fn link(
            &mut self,
            src: f64,
            dst: f64,
            label: Option<String>,
            weight: Option<f64>,
        ) -> napi::Result<()> {
            let label = label.as_deref().unwrap_or("related");
            let weight = weight.unwrap_or(1.0) as f32;
            dispatch!(self, mut db => db.link(src as u64, dst as u64, label, weight))
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        /// 断开两节点间的所有边
        #[napi]
        pub fn unlink(&mut self, src: f64, dst: f64) -> napi::Result<()> {
            dispatch!(self, mut db => db.unlink(src as u64, dst as u64))
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        /// 获取 N 跳邻居节点 ID 列表
        #[napi]
        pub fn neighbors(&self, id: f64, depth: Option<u32>) -> Vec<f64> {
            let depth = depth.unwrap_or(1) as usize;
            dispatch!(self, db => db.neighbors(id as u64, depth))
                .into_iter()
                .map(|id| id as f64)
                .collect()
        }

        // ── 向量检索 ──

        /// 混合检索:向量锚定 + 图谱扩散
        #[napi]
        pub fn search(
            &self,
            query_vector: Vec<f64>,
            top_k: Option<u32>,
            expand_depth: Option<u32>,
            min_score: Option<f64>,
        ) -> napi::Result<Vec<JsSearchHit>> {
            let top_k = top_k.unwrap_or(5) as usize;
            let expand_depth = expand_depth.unwrap_or(0) as usize;
            let min_score = min_score.unwrap_or(0.5) as f32;

            let hits = match &self.inner {
                DbBackend::F32(db) => {
                    let v: Vec<f32> = query_vector.iter().map(|&x| x as f32).collect();
                    db.search(&v, top_k, expand_depth, min_score)
                }
                DbBackend::F16(db) => {
                    let v: Vec<half::f16> = query_vector
                        .iter()
                        .map(|&x| half::f16::from_f64(x))
                        .collect();
                    db.search(&v, top_k, expand_depth, min_score)
                }
                DbBackend::U64(db) => {
                    let v: Vec<u64> = query_vector.iter().map(|&x| x as u64).collect();
                    db.search(&v, top_k, expand_depth, min_score)
                }
            }
            .map_err(|e| napi::Error::from_reason(e.to_string()))?;

            Ok(hits
                .into_iter()
                .map(|h| JsSearchHit {
                    id: h.id as f64,
                    score: h.score as f64,
                    payload: h.payload,
                })
                .collect())
        }

        /// 认知检索引擎:完全参数化暴露的高级功能 (FISTA, DPP, PPR)
        #[napi]
        pub fn search_advanced(
            &self,
            query_vector: Vec<f64>,
            config: Option<JsSearchConfig>,
        ) -> napi::Result<Vec<JsSearchHit>> {
            let cfg = config.unwrap_or(JsSearchConfig {
                top_k: None,
                expand_depth: None,
                min_score: None,
                teleport_alpha: None,
                enable_advanced_pipeline: None,
                enable_sparse_residual: None,
                fista_lambda: None,
                fista_threshold: None,
                enable_dpp: None,
                dpp_quality_weight: None,
                enable_refractory_fatigue: None,
                custom_query_text: None,
                enable_text_hybrid_search: None,
                text_boost: None,
                bq_candidate_ratio: None,
            });

            let core_config = crate::database::SearchConfig {
                top_k: cfg.top_k.unwrap_or(5) as usize,
                expand_depth: cfg.expand_depth.unwrap_or(2) as usize,
                min_score: cfg.min_score.unwrap_or(0.1) as f32,
                teleport_alpha: cfg.teleport_alpha.unwrap_or(0.0) as f32,
                enable_advanced_pipeline: cfg.enable_advanced_pipeline.unwrap_or(true),
                enable_sparse_residual: cfg.enable_sparse_residual.unwrap_or(false),
                fista_lambda: cfg.fista_lambda.unwrap_or(0.1) as f32,
                fista_threshold: cfg.fista_threshold.unwrap_or(0.3) as f32,
                enable_dpp: cfg.enable_dpp.unwrap_or(false),
                dpp_quality_weight: cfg.dpp_quality_weight.unwrap_or(1.0) as f32,
                enable_refractory_fatigue: cfg.enable_refractory_fatigue.unwrap_or(false),
                enable_text_hybrid_search: cfg.enable_text_hybrid_search.unwrap_or(false),
                text_boost: cfg.text_boost.unwrap_or(1.5) as f32,
                bq_candidate_ratio: cfg.bq_candidate_ratio.unwrap_or(0.05) as f32,
                ..Default::default()
            };

            let q_text = cfg.custom_query_text.as_deref();

            let hits = match &self.inner {
                DbBackend::F32(db) => {
                    let v: Vec<f32> = query_vector.iter().map(|&x| x as f32).collect();
                    db.search_hybrid(q_text, Some(&v), &core_config)
                }
                DbBackend::F16(db) => {
                    let v: Vec<half::f16> = query_vector
                        .iter()
                        .map(|&x| half::f16::from_f64(x))
                        .collect();
                    db.search_hybrid(q_text, Some(&v), &core_config)
                }
                DbBackend::U64(db) => {
                    let v: Vec<u64> = query_vector.iter().map(|&x| x as u64).collect();
                    db.search_hybrid(q_text, Some(&v), &core_config)
                }
            }
            .map_err(|e| napi::Error::from_reason(e.to_string()))?;

            Ok(hits
                .into_iter()
                .map(|h| JsSearchHit {
                    id: h.id as f64,
                    score: h.score as f64,
                    payload: h.payload,
                })
                .collect())
        }

        /// 混合检索增强入口:带图扩散的双路检索
        #[napi]
        pub fn search_hybrid(
            &self,
            query_vector: Vec<f64>,
            query_text: String,
            top_k: Option<u32>,
            expand_depth: Option<u32>,
            min_score: Option<f64>,
            hybrid_alpha: Option<f64>,
        ) -> napi::Result<Vec<JsSearchHit>> {
            let top_k = top_k.unwrap_or(5) as usize;
            let expand_depth = expand_depth.unwrap_or(2) as usize;
            let min_score = min_score.unwrap_or(0.1) as f32;
            let alpha = hybrid_alpha.unwrap_or(0.7) as f32;
            // 简单的启发式权重换算
            let boost = (1.0 - alpha).max(0.1) * 3.0;

            let core_config = crate::database::SearchConfig {
                top_k,
                expand_depth,
                min_score,
                enable_text_hybrid_search: true,
                text_boost: boost,
                ..Default::default()
            };

            let hits = match &self.inner {
                DbBackend::F32(db) => {
                    let v: Vec<f32> = query_vector.iter().map(|&x| x as f32).collect();
                    db.search_hybrid(Some(&query_text), Some(&v), &core_config)
                }
                DbBackend::F16(db) => {
                    let v: Vec<half::f16> = query_vector
                        .iter()
                        .map(|&x| half::f16::from_f64(x))
                        .collect();
                    db.search_hybrid(Some(&query_text), Some(&v), &core_config)
                }
                DbBackend::U64(db) => {
                    let v: Vec<u64> = query_vector.iter().map(|&x| x as u64).collect();
                    db.search_hybrid(Some(&query_text), Some(&v), &core_config)
                }
            }
            .map_err(|e| napi::Error::from_reason(e.to_string()))?;

            Ok(hits
                .into_iter()
                .map(|h| JsSearchHit {
                    id: h.id as f64,
                    score: h.score as f64,
                    payload: h.payload,
                })
                .collect())
        }

        // ── 文本索引 ──

        /// 对节点建立用于双路召回的长文本 BM25 索引
        #[napi]
        pub fn index_text(&mut self, id: f64, text: String) -> napi::Result<()> {
            dispatch!(self, mut db => db.index_text(id as u64, &text))
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        /// 对节点建立用于精确命中的 AC自动机 高级关键词索引
        #[napi]
        pub fn index_keyword(&mut self, id: f64, keyword: String) -> napi::Result<()> {
            dispatch!(self, mut db => db.index_keyword(id as u64, &keyword))
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        /// 在批量插入或重启后必须调用,用于重编译自动机与词频
        #[napi]
        pub fn build_text_index(&mut self) {
            let _ = dispatch!(self, mut db => db.build_text_index());
        }

        // ── 元数据过滤 ──

        /// 类 MongoDB 语法条件过滤,返回匹配节点列表
        #[napi]
        pub fn filter_where(&self, condition: serde_json::Value) -> napi::Result<Vec<JsNodeView>> {
            let filter = json_to_filter(&condition)?;
            let views = match &self.inner {
                DbBackend::F32(db) => db
                    .filter_where(&filter)
                    .into_iter()
                    .map(|n| {
                        let edges_arr = n.edges
                            .into_iter()
                            .map(|e| JsEdge {
                                target_id: e.target_id as f64,
                                label: e.label,
                                weight: e.weight as f64,
                            })
                            .collect::<Vec<_>>();
                        JsNodeView {
                            id: n.id as f64,
                            vector: n.vector.iter().map(|&x| x as f64).collect(),
                            payload: n.payload,
                            num_edges: edges_arr.len() as u32,
                            edges: edges_arr,
                        }
                    })
                    .collect::<Vec<_>>(),
                DbBackend::F16(db) => db
                    .filter_where(&filter)
                    .into_iter()
                    .map(|n| {
                        let edges_arr = n.edges
                            .into_iter()
                            .map(|e| JsEdge {
                                target_id: e.target_id as f64,
                                label: e.label,
                                weight: e.weight as f64,
                            })
                            .collect::<Vec<_>>();
                        JsNodeView {
                            id: n.id as f64,
                            vector: n.vector.iter().map(|x| x.to_f64()).collect(),
                            payload: n.payload,
                            num_edges: edges_arr.len() as u32,
                            edges: edges_arr,
                        }
                    })
                    .collect::<Vec<_>>(),
                DbBackend::U64(db) => db
                    .filter_where(&filter)
                    .into_iter()
                    .map(|n| {
                        let edges_arr = n.edges
                            .into_iter()
                            .map(|e| JsEdge {
                                target_id: e.target_id as f64,
                                label: e.label,
                                weight: e.weight as f64,
                            })
                            .collect::<Vec<_>>();
                        JsNodeView {
                            id: n.id as f64,
                            vector: n.vector.iter().map(|&x| x as f64).collect(),
                            payload: n.payload,
                            num_edges: edges_arr.len() as u32,
                            edges: edges_arr,
                        }
                    })
                    .collect::<Vec<_>>(),
            };
            Ok(views)
        }

        // ── Cypher 图谱查询 ──

        /// 执行类 Cypher 查询,返回每行变量绑定的 JSON 数组
        ///
        /// 每个结果行是 `{ varName: { id, payload, numEdges } }` 结构的对象
        #[napi]
        pub fn query(&self, cypher: String) -> napi::Result<Vec<serde_json::Value>> {
            // 辅助闭包:将一个 row(HashMap) 转成 serde_json::Value
            fn row_to_json<T: crate::vector::VectorType>(
                row: std::collections::HashMap<String, crate::node::NodeView<T>>,
            ) -> serde_json::Value {
                let mut obj = serde_json::Map::new();
                for (var_name, node) in row {
                    obj.insert(
                        var_name,
                        serde_json::json!({
                            "id": node.id,
                            "payload": node.payload,
                            "numEdges": node.edges.len(),
                        }),
                    );
                }
                serde_json::Value::Object(obj)
            }

            match &self.inner {
                DbBackend::F32(db) => db
                    .query(&cypher)
                    .map_err(|e| napi::Error::from_reason(e.to_string()))
                    .map(|rows| rows.into_iter().map(row_to_json).collect()),
                DbBackend::F16(db) => db
                    .query(&cypher)
                    .map_err(|e| napi::Error::from_reason(e.to_string()))
                    .map(|rows| rows.into_iter().map(row_to_json).collect()),
                DbBackend::U64(db) => db
                    .query(&cypher)
                    .map_err(|e| napi::Error::from_reason(e.to_string()))
                    .map(|rows| rows.into_iter().map(row_to_json).collect()),
            }
        }

        // ── 持久化与管理 ──

        /// 手动落盘
        #[napi]
        pub fn flush(&mut self) -> napi::Result<()> {
            dispatch!(self, mut db => db.flush())
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        /// 运行时切换 WAL 同步模式
        #[napi]
        pub fn set_sync_mode(&mut self, mode: String) -> napi::Result<()> {
            let sm = parse_sync_mode(&mode)?;
            dispatch!(self, mut db => db.set_sync_mode(sm));
            Ok(())
        }

        /// 启动后台自动压缩(每 interval_secs 秒落盘一次)
        #[napi]
        pub fn enable_auto_compaction(&mut self, interval_secs: Option<u32>) {
            let secs = interval_secs.unwrap_or(30) as u64;
            dispatch!(self, mut db => db.enable_auto_compaction(std::time::Duration::from_secs(secs)));
        }

        /// 停止后台自动压缩
        #[napi]
        pub fn disable_auto_compaction(&mut self) {
            dispatch!(self, mut db => db.disable_auto_compaction());
        }

        /// 手动触发全量压实(阻塞当前线程)
        #[napi]
        pub fn compact(&mut self) -> napi::Result<()> {
            dispatch!(self, mut db => db.compact())
                .map_err(|e| napi::Error::from_reason(e.to_string()))
        }

        /// 设置内存上限(MB),0 = 无限制
        #[napi]
        pub fn set_memory_limit(&mut self, mb: u32) {
            dispatch!(self, mut db => db.set_memory_limit(mb as usize * 1024 * 1024));
        }

        /// 估算当前内存占用(字节)
        #[napi]
        pub fn estimated_memory(&self) -> f64 {
            dispatch!(self, db => db.estimated_memory()) as f64
        }

        /// 获取向量维度
        #[napi]
        pub fn dim(&self) -> u32 {
            dispatch!(self, db => db.dim()) as u32
        }

        /// 获取节点总数
        #[napi]
        pub fn node_count(&self) -> u32 {
            dispatch!(self, db => db.node_count()) as u32
        }

        /// 获取所有活跃节点 ID
        #[napi]
        pub fn all_node_ids(&self) -> Vec<f64> {
            dispatch!(self, db => db.all_node_ids())
                .into_iter()
                .map(|id| id as f64)
                .collect()
        }

        /// 维度迁移:结构复制到新维度数据库,返回需要更新向量的节点 ID 列表
        #[napi]
        pub fn migrate(&self, new_path: String, new_dim: u32) -> napi::Result<Vec<f64>> {
            match &self.inner {
                DbBackend::F32(db) => {
                    let (_, ids) = db
                        .migrate_to(&new_path, new_dim as usize)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))?;
                    Ok(ids.into_iter().map(|id| id as f64).collect())
                }
                DbBackend::F16(db) => {
                    let (_, ids) = db
                        .migrate_to(&new_path, new_dim as usize)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))?;
                    Ok(ids.into_iter().map(|id| id as f64).collect())
                }
                DbBackend::U64(db) => {
                    let (_, ids) = db
                        .migrate_to(&new_path, new_dim as usize)
                        .map_err(|e| napi::Error::from_reason(e.to_string()))?;
                    Ok(ids.into_iter().map(|id| id as f64).collect())
                }
            }
        }

        /// 获取 dtype 字符串("f32" / "f16" / "u64")
        #[napi(getter)]
        pub fn dtype(&self) -> String {
            self.dtype.clone()
        }
    } // impl TriviumDB
} // mod nodejs