oxirs-tdb 0.3.1

Apache Jena TDB/TDB2 compatible RDF storage engine with B+Tree indexes
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
//! Full-text search index for RDF literal values using Tantivy.
//!
//! Provides:
//! - [`TextSearchIndex`]: Tantivy-backed index for RDF literals stored in TDB.
//! - [`TextPropertyFunction`]: Evaluates SPARQL `text:query(?subject, "terms")`.
//!
//! Two storage modes:
//! - **In-memory** (`TextSearchConfig { index_path: None, .. }`): fast, ephemeral, for tests.
//! - **On-disk** (`index_path: Some(dir)`): durable, production-ready.

use std::path::PathBuf;
use std::sync::Arc;

use log::{debug, warn};
use parking_lot::RwLock;
use tantivy::collector::TopDocs;
use tantivy::query::QueryParser;
use tantivy::schema::{SchemaBuilder, Value, STORED, STRING, TEXT};
use tantivy::{Index, IndexReader, IndexWriter, ReloadPolicy, TantivyDocument, Term};

use crate::error::{Result, TdbError};

// ─────────────────────────────────────────────────────────────────────────────
// Configuration
// ─────────────────────────────────────────────────────────────────────────────

/// Configuration for [`TextSearchIndex`].
#[derive(Debug, Clone)]
pub struct TextSearchConfig {
    /// Directory for the Tantivy index.  `None` creates a RAM-based index.
    pub index_path: Option<PathBuf>,
    /// Tantivy writer heap budget in megabytes (default 50 MB).
    pub heap_size_mb: usize,
    /// Auto-commit the writer after accumulating this many staged documents.
    /// `0` disables auto-commit (manual `commit()` only).
    pub commit_threshold: usize,
}

impl Default for TextSearchConfig {
    fn default() -> Self {
        Self {
            index_path: None,
            heap_size_mb: 50,
            commit_threshold: 1_000,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Input / output types
// ─────────────────────────────────────────────────────────────────────────────

/// An RDF literal to be indexed.
#[derive(Debug, Clone)]
pub struct LiteralDocument {
    /// IRI (or blank-node ID) of the triple's subject.
    pub subject: String,
    /// IRI of the triple's predicate.
    pub predicate: String,
    /// BCP-47 language tag, e.g. `"en"` or `"de"`.  `None` for untagged literals.
    pub lang: Option<String>,
    /// Literal text value.
    pub value: String,
}

/// A single full-text search hit.
#[derive(Debug, Clone)]
pub struct TextSearchResult {
    /// Subject IRI.
    pub subject: String,
    /// Predicate IRI.
    pub predicate: String,
    /// Matched literal text.
    pub value: String,
    /// BM25-based relevance score from Tantivy.
    pub score: f32,
    /// Language tag if the literal was tagged.
    pub lang: Option<String>,
}

// ─────────────────────────────────────────────────────────────────────────────
// Internal schema field names
// ─────────────────────────────────────────────────────────────────────────────

const FIELD_SUBJECT: &str = "subject";
const FIELD_PREDICATE: &str = "predicate";
const FIELD_LANG: &str = "lang";
const FIELD_VALUE: &str = "value";

// ─────────────────────────────────────────────────────────────────────────────
// TextSearchIndex
// ─────────────────────────────────────────────────────────────────────────────

/// Full-text search index over RDF literals, backed by Tantivy.
///
/// Thread-safe via internal [`RwLock`] over the [`IndexWriter`].
pub struct TextSearchIndex {
    /// Tantivy index (may be RAM-backed or directory-backed).
    index: Index,
    /// Tantivy index writer wrapped in a lock so it can be shared.
    writer: Arc<RwLock<IndexWriter>>,
    /// Near-real-time reader for searches.
    reader: IndexReader,
    /// Compiled schema.
    schema: tantivy::schema::Schema,
    /// Schema field: subject IRI.
    field_subject: tantivy::schema::Field,
    /// Schema field: predicate IRI.
    field_predicate: tantivy::schema::Field,
    /// Schema field: language tag.
    field_lang: tantivy::schema::Field,
    /// Schema field: literal text (full-text indexed).
    field_value: tantivy::schema::Field,
    /// Auto-commit threshold (0 = disabled).
    commit_threshold: usize,
    /// Number of documents staged since the last commit.
    staged_count: usize,
}

impl TextSearchIndex {
    // ── Constructor ──────────────────────────────────────────────────────────

    /// Create or open a [`TextSearchIndex`] according to `config`.
    ///
    /// If `config.index_path` is `None` an in-memory (RAM) index is used.
    /// Otherwise the directory is created if it does not already exist and
    /// a persistent disk index is opened (or created on first use).
    pub fn new(config: TextSearchConfig) -> Result<Self> {
        let heap_bytes = config
            .heap_size_mb
            .saturating_mul(1024 * 1024)
            .max(15_000_000);

        // Build schema
        let mut builder = SchemaBuilder::new();
        let field_subject = builder.add_text_field(FIELD_SUBJECT, STRING | STORED);
        let field_predicate = builder.add_text_field(FIELD_PREDICATE, STRING | STORED);
        let field_lang = builder.add_text_field(FIELD_LANG, STRING | STORED);
        let field_value = builder.add_text_field(FIELD_VALUE, TEXT | STORED);
        let schema = builder.build();

        let index = match config.index_path {
            Some(ref dir) => {
                std::fs::create_dir_all(dir).map_err(TdbError::Io)?;
                // Try to create; fall back to opening an existing index.
                Index::create_in_dir(dir, schema.clone())
                    .or_else(|_| Index::open_in_dir(dir))
                    .map_err(|e| TdbError::Other(format!("Tantivy index open failed: {e}")))?
            }
            None => Index::create_in_ram(schema.clone()),
        };

        let writer = index
            .writer(heap_bytes)
            .map_err(|e| TdbError::Other(format!("Tantivy writer creation failed: {e}")))?;

        // Manual reload: new documents become visible only after explicit commit + reload.
        let reader = index
            .reader_builder()
            .reload_policy(ReloadPolicy::Manual)
            .try_into()
            .map_err(|e| TdbError::Other(format!("Tantivy reader creation failed: {e}")))?;

        Ok(Self {
            index,
            writer: Arc::new(RwLock::new(writer)),
            reader,
            schema,
            field_subject,
            field_predicate,
            field_lang,
            field_value,
            commit_threshold: config.commit_threshold,
            staged_count: 0,
        })
    }

    // ── Write operations ─────────────────────────────────────────────────────

    /// Add a single RDF literal document to the index.
    ///
    /// Does **not** commit automatically unless the configured
    /// `commit_threshold` is reached.
    pub fn add_literal(&mut self, doc: LiteralDocument) -> Result<()> {
        self.add_tantivy_document(&doc)?;
        self.staged_count += 1;

        if self.commit_threshold > 0 && self.staged_count >= self.commit_threshold {
            self.commit()?;
        }

        Ok(())
    }

    /// Add a batch of RDF literal documents.
    ///
    /// Returns the number of documents successfully staged.
    /// A single `commit()` is performed at the end of the batch if any documents
    /// were added.
    pub fn add_literals_batch(&mut self, docs: Vec<LiteralDocument>) -> Result<u64> {
        if docs.is_empty() {
            return Ok(0);
        }

        let mut count: u64 = 0;
        for doc in docs {
            self.add_tantivy_document(&doc)?;
            count += 1;
        }

        self.staged_count += count as usize;
        self.commit()?;

        Ok(count)
    }

    /// Commit all staged documents to the Tantivy index and reload the reader
    /// so that subsequent searches reflect the new data.
    pub fn commit(&mut self) -> Result<()> {
        {
            let mut writer = self.writer.write();
            writer
                .commit()
                .map_err(|e| TdbError::Other(format!("Tantivy commit failed: {e}")))?;
        }

        self.reader
            .reload()
            .map_err(|e| TdbError::Other(format!("Tantivy reader reload failed: {e}")))?;

        self.staged_count = 0;
        debug!("TextSearchIndex committed and reader reloaded");
        Ok(())
    }

    // ── Read operations ──────────────────────────────────────────────────────

    /// Search for the given free-text `query` string.
    ///
    /// Returns up to `limit` results ordered by descending BM25 score.
    pub fn search(&self, query: &str, limit: usize) -> Result<Vec<TextSearchResult>> {
        self.run_search(query, None, None, limit)
    }

    /// Search restricted to documents whose `predicate` field equals the given
    /// predicate IRI.
    pub fn search_with_predicate(
        &self,
        query: &str,
        predicate: &str,
        limit: usize,
    ) -> Result<Vec<TextSearchResult>> {
        self.run_search(query, Some(predicate), None, limit)
    }

    /// Search restricted to documents whose `lang` field equals the given
    /// BCP-47 language tag (e.g. `"en"`).
    pub fn search_lang(
        &self,
        query: &str,
        lang: &str,
        limit: usize,
    ) -> Result<Vec<TextSearchResult>> {
        self.run_search(query, None, Some(lang), limit)
    }

    /// Delete every document whose `subject` field equals the given IRI.
    ///
    /// The deletion is staged in the writer buffer.  Call [`commit`](Self::commit)
    /// to make it durable.  Returns the number of documents that were staged for
    /// deletion (estimated from the searcher before deletion).
    pub fn delete_by_subject(&mut self, subject: &str) -> Result<u64> {
        let before = self.document_count()?;

        let term = Term::from_field_text(self.field_subject, subject);
        {
            let writer = self.writer.write();
            writer.delete_term(term);
        }

        // Commit immediately so the reader is consistent.
        self.commit()?;

        let after = self.document_count()?;
        Ok(before.saturating_sub(after))
    }

    /// Return the total number of documents currently visible in the index.
    pub fn document_count(&self) -> Result<u64> {
        Ok(self.reader.searcher().num_docs())
    }

    /// Force a reader reload from the latest committed state.
    ///
    /// Useful when the writer has been committed by another path (e.g. from a
    /// clone of the writer [`Arc`]).
    pub fn reload(&mut self) -> Result<()> {
        self.reader
            .reload()
            .map_err(|e| TdbError::Other(format!("Tantivy reader reload failed: {e}")))?;
        Ok(())
    }

    // ── Internal helpers ─────────────────────────────────────────────────────

    /// Build a Tantivy document from a [`LiteralDocument`] and add it to the writer.
    fn add_tantivy_document(&self, doc: &LiteralDocument) -> Result<()> {
        let mut tdoc = TantivyDocument::default();
        tdoc.add_text(self.field_subject, &doc.subject);
        tdoc.add_text(self.field_predicate, &doc.predicate);
        tdoc.add_text(self.field_lang, doc.lang.as_deref().unwrap_or(""));
        tdoc.add_text(self.field_value, &doc.value);

        let writer = self.writer.write();
        writer
            .add_document(tdoc)
            .map_err(|e| TdbError::Other(format!("Tantivy add_document failed: {e}")))?;

        Ok(())
    }

    /// Core search implementation.
    ///
    /// After retrieving Tantivy hits, optional post-filters are applied for
    /// `predicate` and `lang` because Tantivy's schema stores those fields as
    /// `STRING` (exact-match, not full-text) and we need exact equality checks
    /// on stored values.
    fn run_search(
        &self,
        query: &str,
        predicate_filter: Option<&str>,
        lang_filter: Option<&str>,
        limit: usize,
    ) -> Result<Vec<TextSearchResult>> {
        if query.is_empty() {
            return Ok(Vec::new());
        }

        let searcher = self.reader.searcher();
        let query_parser = QueryParser::for_index(&self.index, vec![self.field_value]);

        let parsed_query = query_parser
            .parse_query(query)
            .map_err(|e| TdbError::Other(format!("Tantivy query parse error: {e}")))?;

        // Fetch more results than `limit` to account for post-filtering.
        let fetch_limit = if predicate_filter.is_some() || lang_filter.is_some() {
            limit.saturating_mul(10).max(limit + 50)
        } else {
            limit
        };

        let top_docs = searcher
            .search(
                &parsed_query,
                &TopDocs::with_limit(fetch_limit).order_by_score(),
            )
            .map_err(|e| TdbError::Other(format!("Tantivy search error: {e}")))?;

        let mut results = Vec::with_capacity(top_docs.len());

        for (score, doc_addr) in top_docs {
            match searcher.doc::<TantivyDocument>(doc_addr) {
                Ok(tdoc) => {
                    let subject = get_stored_str(&tdoc, self.field_subject);
                    let predicate = get_stored_str(&tdoc, self.field_predicate);
                    let lang_raw = get_stored_str(&tdoc, self.field_lang);
                    let value = get_stored_str(&tdoc, self.field_value);
                    let lang = if lang_raw.is_empty() {
                        None
                    } else {
                        Some(lang_raw)
                    };

                    // Post-filter: predicate
                    if let Some(pf) = predicate_filter {
                        if predicate != pf {
                            continue;
                        }
                    }

                    // Post-filter: language
                    if let Some(lf) = lang_filter {
                        match &lang {
                            Some(l) if l == lf => {}
                            _ => continue,
                        }
                    }

                    results.push(TextSearchResult {
                        subject,
                        predicate,
                        value,
                        score,
                        lang,
                    });

                    if results.len() >= limit {
                        break;
                    }
                }
                Err(e) => {
                    warn!("Failed to retrieve Tantivy document: {}", e);
                }
            }
        }

        Ok(results)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// SPARQL text: property function interface
// ─────────────────────────────────────────────────────────────────────────────

/// Evaluates the SPARQL `text:query(?subject, "search terms")` property function.
///
/// This struct holds a shared reference to the underlying [`TextSearchIndex`]
/// so that it can be cloned cheaply and used from multiple query-execution
/// contexts.
pub struct TextPropertyFunction {
    index: Arc<RwLock<TextSearchIndex>>,
}

impl TextPropertyFunction {
    /// Default limit used when the caller does not specify one.
    pub const DEFAULT_LIMIT: usize = 100;

    /// Create a new property function wrapper around a shared index.
    pub fn new(index: Arc<RwLock<TextSearchIndex>>) -> Self {
        Self { index }
    }

    /// Evaluate `text:query(?subject, "query_text")`.
    ///
    /// Returns a list of subject IRIs whose associated literals match
    /// `query_text`, ordered by descending relevance score.
    ///
    /// `limit` caps the result set.  Pass `None` to use [`DEFAULT_LIMIT`](Self::DEFAULT_LIMIT).
    pub fn evaluate(&self, query_text: &str, limit: Option<usize>) -> Result<Vec<String>> {
        let effective_limit = limit.unwrap_or(Self::DEFAULT_LIMIT);
        let idx = self.index.read();
        let hits = idx.search(query_text, effective_limit)?;
        // Deduplicate: a subject may match on multiple literals.
        let mut seen = std::collections::HashSet::new();
        let subjects = hits
            .into_iter()
            .filter_map(|r| {
                if seen.insert(r.subject.clone()) {
                    Some(r.subject)
                } else {
                    None
                }
            })
            .collect();
        Ok(subjects)
    }

    /// Evaluate with an additional predicate restriction.
    ///
    /// Only literals whose predicate equals `predicate` are considered.
    pub fn evaluate_with_predicate(
        &self,
        query_text: &str,
        predicate: &str,
        limit: Option<usize>,
    ) -> Result<Vec<String>> {
        let effective_limit = limit.unwrap_or(Self::DEFAULT_LIMIT);
        let idx = self.index.read();
        let hits = idx.search_with_predicate(query_text, predicate, effective_limit)?;
        let mut seen = std::collections::HashSet::new();
        let subjects = hits
            .into_iter()
            .filter_map(|r| {
                if seen.insert(r.subject.clone()) {
                    Some(r.subject)
                } else {
                    None
                }
            })
            .collect();
        Ok(subjects)
    }

    /// Evaluate with an additional language-tag restriction.
    ///
    /// Only literals tagged with `lang` (e.g. `"en"`) are considered.
    pub fn evaluate_with_lang(
        &self,
        query_text: &str,
        lang: &str,
        limit: Option<usize>,
    ) -> Result<Vec<String>> {
        let effective_limit = limit.unwrap_or(Self::DEFAULT_LIMIT);
        let idx = self.index.read();
        let hits = idx.search_lang(query_text, lang, effective_limit)?;
        let mut seen = std::collections::HashSet::new();
        let subjects = hits
            .into_iter()
            .filter_map(|r| {
                if seen.insert(r.subject.clone()) {
                    Some(r.subject)
                } else {
                    None
                }
            })
            .collect();
        Ok(subjects)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Helper
// ─────────────────────────────────────────────────────────────────────────────

/// Extract the first stored string value for `field` from a Tantivy document.
fn get_stored_str(doc: &TantivyDocument, field: tantivy::schema::Field) -> String {
    doc.get_first(field)
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string()
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    /// Build a minimal in-memory [`TextSearchConfig`].
    fn mem_config() -> TextSearchConfig {
        TextSearchConfig {
            index_path: None,
            heap_size_mb: 15,
            commit_threshold: 0, // manual commit in tests
        }
    }

    /// Build a [`LiteralDocument`] with default English language tag.
    fn make_doc(subject: &str, predicate: &str, value: &str) -> LiteralDocument {
        LiteralDocument {
            subject: subject.to_string(),
            predicate: predicate.to_string(),
            lang: Some("en".to_string()),
            value: value.to_string(),
        }
    }

    /// Build a [`LiteralDocument`] with a specific language tag.
    fn make_doc_lang(subject: &str, predicate: &str, value: &str, lang: &str) -> LiteralDocument {
        LiteralDocument {
            subject: subject.to_string(),
            predicate: predicate.to_string(),
            lang: Some(lang.to_string()),
            value: value.to_string(),
        }
    }

    // ── 1. In-memory index creation ──────────────────────────────────────────

    #[test]
    fn test_in_memory_index_creation() {
        let idx = TextSearchIndex::new(mem_config());
        assert!(
            idx.is_ok(),
            "Should create an in-memory index without error"
        );
        let idx = idx.expect("index creation failed");
        let count = idx.document_count().expect("doc count failed");
        assert_eq!(count, 0, "New index should be empty");
    }

    // ── 2. Add and search literal ─────────────────────────────────────────────

    #[test]
    fn test_add_and_search_literal() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/title",
            "Rust programming systems language",
        ))
        .expect("add_literal");
        idx.commit().expect("commit");

        let results = idx.search("rust programming", 10).expect("search");
        assert!(!results.is_empty(), "Expected at least one result");
        assert_eq!(results[0].subject, "http://ex.org/s1");
        assert!(results[0].score > 0.0, "Score must be positive");
    }

    // ── 3. Search with predicate filter ──────────────────────────────────────

    #[test]
    fn test_search_with_predicate_filter() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");

        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/title",
            "semantic web ontology",
        ))
        .expect("add 1");
        idx.add_literal(make_doc(
            "http://ex.org/s2",
            "http://ex.org/description",
            "semantic reasoning engine",
        ))
        .expect("add 2");
        idx.commit().expect("commit");

        // Only the document with predicate "title" should be returned.
        let results = idx
            .search_with_predicate("semantic", "http://ex.org/title", 10)
            .expect("search_with_predicate");
        assert_eq!(results.len(), 1, "Should return exactly one result");
        assert_eq!(results[0].subject, "http://ex.org/s1");
        assert_eq!(results[0].predicate, "http://ex.org/title");
    }

    // ── 4. Search with language filter ──────────────────────────────────────

    #[test]
    fn test_search_with_lang_filter() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");

        idx.add_literal(make_doc_lang(
            "http://ex.org/s1",
            "http://ex.org/label",
            "knowledge graph",
            "en",
        ))
        .expect("add en");
        idx.add_literal(make_doc_lang(
            "http://ex.org/s2",
            "http://ex.org/label",
            "Wissensgraph",
            "de",
        ))
        .expect("add de");
        idx.commit().expect("commit");

        let en_results = idx.search_lang("knowledge", "en", 10).expect("search en");
        assert_eq!(en_results.len(), 1);
        assert_eq!(en_results[0].subject, "http://ex.org/s1");
        assert_eq!(en_results[0].lang, Some("en".to_string()));

        let de_results = idx
            .search_lang("Wissensgraph", "de", 10)
            .expect("search de");
        assert_eq!(de_results.len(), 1);
        assert_eq!(de_results[0].subject, "http://ex.org/s2");
    }

    // ── 5. Delete by subject ─────────────────────────────────────────────────

    #[test]
    fn test_delete_by_subject() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");

        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/p",
            "hello world",
        ))
        .expect("add 1");
        idx.add_literal(make_doc(
            "http://ex.org/s2",
            "http://ex.org/p",
            "hello rust",
        ))
        .expect("add 2");
        idx.commit().expect("commit");

        let deleted = idx.delete_by_subject("http://ex.org/s1").expect("delete");
        assert_eq!(deleted, 1, "Should have deleted one document");

        let results = idx.search("hello", 10).expect("search after delete");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].subject, "http://ex.org/s2");
    }

    // ── 6. Batch add ─────────────────────────────────────────────────────────

    #[test]
    fn test_batch_add() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");

        let docs = vec![
            make_doc("http://ex.org/a", "http://ex.org/p", "apple fruit healthy"),
            make_doc(
                "http://ex.org/b",
                "http://ex.org/p",
                "banana tropical fruit",
            ),
            make_doc("http://ex.org/c", "http://ex.org/p", "cherry red fruit"),
        ];

        let count = idx.add_literals_batch(docs).expect("batch add");
        assert_eq!(count, 3, "All three documents should be staged");

        let results = idx.search("fruit", 10).expect("search fruit");
        assert_eq!(results.len(), 3, "All three fruit documents should match");
    }

    // ── 7. Document count ─────────────────────────────────────────────────────

    #[test]
    fn test_document_count() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        assert_eq!(idx.document_count().expect("count"), 0);

        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/p",
            "first document",
        ))
        .expect("add 1");
        idx.commit().expect("commit after 1");
        assert_eq!(idx.document_count().expect("count after 1"), 1);

        idx.add_literal(make_doc(
            "http://ex.org/s2",
            "http://ex.org/p",
            "second document",
        ))
        .expect("add 2");
        idx.add_literal(make_doc(
            "http://ex.org/s3",
            "http://ex.org/p",
            "third document",
        ))
        .expect("add 3");
        idx.commit().expect("commit after 3");
        assert_eq!(idx.document_count().expect("count after 3"), 3);
    }

    // ── 8. Property function evaluate ────────────────────────────────────────

    #[test]
    fn test_property_function_evaluate() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/p",
            "sparql query language semantic web",
        ))
        .expect("add 1");
        idx.add_literal(make_doc(
            "http://ex.org/s2",
            "http://ex.org/p",
            "graphql schema definition language",
        ))
        .expect("add 2");
        idx.commit().expect("commit");

        let pf = TextPropertyFunction::new(Arc::new(RwLock::new(idx)));
        let subjects = pf.evaluate("sparql", None).expect("evaluate");
        assert_eq!(subjects.len(), 1);
        assert_eq!(subjects[0], "http://ex.org/s1");
    }

    // ── 9. Property function with predicate restriction ───────────────────────

    #[test]
    fn test_property_function_with_predicate() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://schema.org/name",
            "OxiRS semantic web engine",
        ))
        .expect("add name");
        idx.add_literal(make_doc(
            "http://ex.org/s2",
            "http://schema.org/description",
            "OxiRS is a semantic web platform",
        ))
        .expect("add desc");
        idx.commit().expect("commit");

        let pf = TextPropertyFunction::new(Arc::new(RwLock::new(idx)));
        let subjects = pf
            .evaluate_with_predicate("semantic", "http://schema.org/name", None)
            .expect("evaluate_with_predicate");
        assert_eq!(subjects.len(), 1);
        assert_eq!(subjects[0], "http://ex.org/s1");
    }

    // ── 10. Auto-commit threshold ─────────────────────────────────────────────

    #[test]
    fn test_auto_commit_threshold() {
        let config = TextSearchConfig {
            index_path: None,
            heap_size_mb: 15,
            commit_threshold: 2, // auto-commit every 2 documents
        };
        let mut idx = TextSearchIndex::new(config).expect("index");

        // Add first document: no auto-commit yet (staged_count becomes 1 < 2)
        idx.add_literal(make_doc(
            "http://ex.org/a",
            "http://ex.org/p",
            "tantivy search",
        ))
        .expect("add 1");

        // Add second document: auto-commit triggered (staged_count becomes 2 >= 2)
        idx.add_literal(make_doc(
            "http://ex.org/b",
            "http://ex.org/p",
            "rust indexing",
        ))
        .expect("add 2");

        // After auto-commit both documents should be visible.
        let count = idx.document_count().expect("doc count");
        assert_eq!(count, 2, "Both documents visible after auto-commit");
    }

    // ── 11. On-disk index creation ────────────────────────────────────────────

    #[test]
    fn test_on_disk_index_creation() {
        let dir = env::temp_dir().join(format!("oxirs_tdb_text_search_{}", std::process::id()));
        let config = TextSearchConfig {
            index_path: Some(dir.clone()),
            heap_size_mb: 15,
            commit_threshold: 0,
        };

        {
            let mut idx = TextSearchIndex::new(config.clone()).expect("create on-disk index");
            idx.add_literal(make_doc(
                "http://ex.org/s1",
                "http://ex.org/p",
                "persistent full-text search",
            ))
            .expect("add");
            idx.commit().expect("commit");
            let count = idx.document_count().expect("count");
            assert_eq!(count, 1);
        }

        // Re-open the same directory — document should still be there.
        {
            let idx = TextSearchIndex::new(config).expect("reopen on-disk index");
            let count = idx.document_count().expect("count after reopen");
            assert_eq!(count, 1, "Document should persist after re-opening index");
        }

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ── 12. Empty query returns nothing ──────────────────────────────────────

    #[test]
    fn test_empty_query_returns_nothing() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc("http://ex.org/s1", "http://ex.org/p", "anything"))
            .expect("add");
        idx.commit().expect("commit");

        let results = idx.search("", 10).expect("empty search");
        assert!(
            results.is_empty(),
            "Empty query string should return no results"
        );
    }

    // ── 13. Reload method ─────────────────────────────────────────────────────

    #[test]
    fn test_reload() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/p",
            "reload test content",
        ))
        .expect("add");
        idx.commit().expect("commit");
        // A second reload should succeed without error.
        idx.reload().expect("reload");
        let count = idx.document_count().expect("count");
        assert_eq!(count, 1);
    }

    // ── 14. Multiple literals for same subject (dedup in property function) ───

    #[test]
    fn test_property_function_deduplicates_subjects() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        // Same subject, two different predicates, both matching "knowledge"
        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/title",
            "knowledge graph",
        ))
        .expect("add title");
        idx.add_literal(make_doc(
            "http://ex.org/s1",
            "http://ex.org/description",
            "knowledge representation",
        ))
        .expect("add desc");
        idx.commit().expect("commit");

        let pf = TextPropertyFunction::new(Arc::new(RwLock::new(idx)));
        let subjects = pf.evaluate("knowledge", Some(10)).expect("evaluate");
        // Subject should appear only once despite matching two documents.
        assert_eq!(subjects.len(), 1);
        assert_eq!(subjects[0], "http://ex.org/s1");
    }

    // ── 15. Batch add with lang filter search ─────────────────────────────────

    #[test]
    fn test_batch_add_with_lang_search() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");

        let docs = vec![
            make_doc_lang(
                "http://ex.org/en1",
                "http://ex.org/p",
                "open data linked data",
                "en",
            ),
            make_doc_lang(
                "http://ex.org/fr1",
                "http://ex.org/p",
                "données ouvertes liées",
                "fr",
            ),
            make_doc_lang(
                "http://ex.org/en2",
                "http://ex.org/p",
                "open source data platform",
                "en",
            ),
        ];

        idx.add_literals_batch(docs).expect("batch add");

        let en_results = idx.search_lang("open", "en", 10).expect("en search");
        assert_eq!(en_results.len(), 2, "Should find two English documents");
        for r in &en_results {
            assert_eq!(r.lang, Some("en".to_string()));
        }
    }
    // ── 16. Search with limit of 1 ───────────────────────────────────────────

    #[test]
    fn test_search_limit_one() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        for i in 0..5 {
            idx.add_literal(make_doc(
                &format!("http://ex.org/s{}", i),
                "http://ex.org/p",
                &format!("semantic web technology {}", i),
            ))
            .expect("add");
        }
        idx.commit().expect("commit");

        let results = idx.search("semantic", 1).expect("search");
        assert_eq!(results.len(), 1, "Limit=1 should return at most one result");
    }

    // ── 17. Multiple commits — document count is cumulative ──────────────────

    #[test]
    fn test_multiple_commits_cumulative_count() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc("http://s1", "http://p", "first document"))
            .expect("add");
        idx.commit().expect("commit 1");
        idx.add_literal(make_doc("http://s2", "http://p", "second document"))
            .expect("add");
        idx.commit().expect("commit 2");
        idx.add_literal(make_doc("http://s3", "http://p", "third document"))
            .expect("add");
        idx.commit().expect("commit 3");

        let count = idx.document_count().expect("count");
        assert_eq!(count, 3, "Should have 3 documents after 3 commits");
    }

    // ── 18. Delete non-existent subject returns 0 ────────────────────────────

    #[test]
    fn test_delete_nonexistent_subject_returns_zero() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.commit().expect("commit empty");
        let removed = idx
            .delete_by_subject("http://ghost.org/not_there")
            .expect("delete");
        assert_eq!(
            removed, 0,
            "No documents should be removed for unknown subject"
        );
    }

    // ── 19. Property function returns empty for unknown query ────────────────

    #[test]
    fn test_property_function_unknown_term_returns_empty() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc("http://s1", "http://p", "known content"))
            .expect("add");
        idx.commit().expect("commit");

        let pf = TextPropertyFunction::new(Arc::new(RwLock::new(idx)));
        let results = pf
            .evaluate("xyzzy_nonexistent_term", Some(10))
            .expect("evaluate");
        assert!(results.is_empty());
    }

    // ── 20. Search result contains correct subject and predicate ─────────────

    #[test]
    fn test_search_result_fields() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(LiteralDocument {
            subject: "http://ex.org/doc1".to_string(),
            predicate: "http://schema.org/description".to_string(),
            lang: Some("en".to_string()),
            value: "unique phrase for this test".to_string(),
        })
        .expect("add");
        idx.commit().expect("commit");

        let results = idx.search("unique", 5).expect("search");
        assert_eq!(results.len(), 1);
        let r = &results[0];
        assert_eq!(r.subject, "http://ex.org/doc1");
        assert_eq!(r.predicate, "http://schema.org/description");
        assert!(r.value.contains("unique"));
        assert!(r.score > 0.0);
    }

    // ── 21. Batch add returns correct inserted count ─────────────────────────

    #[test]
    fn test_batch_add_count() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        let docs: Vec<LiteralDocument> = (0..7)
            .map(|i| {
                make_doc(
                    &format!("http://s{}", i),
                    "http://p",
                    &format!("item {}", i),
                )
            })
            .collect();
        let n = idx.add_literals_batch(docs).expect("batch add");
        assert_eq!(n, 7, "Should return the count of inserted documents");
    }

    // ── 22. Delete removes only matching subject ─────────────────────────────

    #[test]
    fn test_delete_removes_only_matching_subject() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc(
            "http://ex.org/keep",
            "http://p",
            "important knowledge",
        ))
        .expect("add keep");
        idx.add_literal(make_doc(
            "http://ex.org/remove",
            "http://p",
            "important knowledge",
        ))
        .expect("add remove");
        idx.commit().expect("commit");

        idx.delete_by_subject("http://ex.org/remove")
            .expect("delete");

        // "keep" subject should still be searchable
        let results = idx.search("important", 10).expect("search");
        let subjects: Vec<&str> = results.iter().map(|r| r.subject.as_str()).collect();
        assert!(
            subjects.contains(&"http://ex.org/keep"),
            "keep subject should remain"
        );
    }

    // ── 23. Search is case-insensitive (standard tokenizer lowercases) ───────

    #[test]
    fn test_search_case_insensitive() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc("http://s1", "http://p", "RDF Knowledge Graph"))
            .expect("add");
        idx.commit().expect("commit");

        let lower = idx.search("rdf", 5).expect("lower search");
        let upper = idx.search("RDF", 5).expect("upper search");
        // Both should find the document (Tantivy standard tokenizer lowercases)
        assert!(
            !lower.is_empty() || !upper.is_empty(),
            "At least one casing should match"
        );
    }

    // ── 24. Document count after delete decreases ────────────────────────────

    #[test]
    fn test_doc_count_after_delete() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc("http://s1", "http://p", "first"))
            .expect("add");
        idx.add_literal(make_doc("http://s2", "http://p", "second"))
            .expect("add");
        idx.commit().expect("commit");

        let before = idx.document_count().expect("count before");
        idx.delete_by_subject("http://s1").expect("delete");

        let after = idx.document_count().expect("count after");
        assert!(
            after <= before,
            "Document count should not increase after delete"
        );
    }

    // ── 25. Property function with language filter ───────────────────────────

    #[test]
    fn test_property_function_with_language_filter() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc_lang(
            "http://s_en",
            "http://p",
            "open linked data",
            "en",
        ))
        .expect("add en");
        idx.add_literal(make_doc_lang(
            "http://s_de",
            "http://p",
            "offene verknüpfte Daten",
            "de",
        ))
        .expect("add de");
        idx.commit().expect("commit");

        let pf = TextPropertyFunction::new(Arc::new(RwLock::new(idx)));
        let en_subjects = pf
            .evaluate_with_lang("open", "en", Some(10))
            .expect("en query");
        assert_eq!(en_subjects.len(), 1);
        assert_eq!(en_subjects[0], "http://s_en");
    }

    // ── 26. Search returns results sorted by descending score ────────────────

    #[test]
    fn test_search_results_ordered_by_relevance() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        // Doc with query term appearing multiple times → higher score
        idx.add_literal(make_doc(
            "http://s_high",
            "http://p",
            "semantic semantic semantic web web web",
        ))
        .expect("add high");
        idx.add_literal(make_doc("http://s_low", "http://p", "semantic"))
            .expect("add low");
        idx.commit().expect("commit");

        let results = idx.search("semantic", 10).expect("search");
        assert!(!results.is_empty());
        // Scores should be non-increasing (highest first)
        for w in results.windows(2) {
            assert!(
                w[0].score >= w[1].score,
                "Results should be ordered by descending score: {} < {}",
                w[0].score,
                w[1].score
            );
        }
    }

    // ── 27. Config: large heap size compiles and works ───────────────────────

    #[test]
    fn test_large_heap_config() {
        let config = TextSearchConfig {
            index_path: None,
            heap_size_mb: 200,
            commit_threshold: 0,
        };
        let mut idx = TextSearchIndex::new(config).expect("large heap index");
        idx.add_literal(make_doc("http://s1", "http://p", "heap test"))
            .expect("add");
        idx.commit().expect("commit");
        assert_eq!(idx.document_count().expect("count"), 1);
    }

    // ── 28. TextSearchResult score is positive ───────────────────────────────

    #[test]
    fn test_search_result_score_positive() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(make_doc("http://s1", "http://p", "score positive check"))
            .expect("add");
        idx.commit().expect("commit");

        let results = idx.search("score", 5).expect("search");
        for r in &results {
            assert!(
                r.score > 0.0,
                "All returned results should have positive scores"
            );
        }
    }

    // ── 29. Multiple subjects matching same query ────────────────────────────

    #[test]
    fn test_multiple_subjects_same_query() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        for i in 0..5 {
            idx.add_literal(make_doc(
                &format!("http://sub{}", i),
                "http://p",
                "sparql query engine",
            ))
            .expect("add");
        }
        idx.commit().expect("commit");

        let results = idx.search("sparql", 10).expect("search");
        assert_eq!(results.len(), 5, "Should find all 5 subjects");
    }

    // ── 30. Search with predicate filter excludes other predicates ───────────

    #[test]
    fn test_search_predicate_filter_excludes_others() {
        let mut idx = TextSearchIndex::new(mem_config()).expect("index");
        idx.add_literal(LiteralDocument {
            subject: "http://s1".to_string(),
            predicate: "http://ex.org/title".to_string(),
            lang: Some("en".to_string()),
            value: "rdf triples storage".to_string(),
        })
        .expect("add title");
        idx.add_literal(LiteralDocument {
            subject: "http://s2".to_string(),
            predicate: "http://ex.org/abstract".to_string(),
            lang: Some("en".to_string()),
            value: "rdf triples storage".to_string(),
        })
        .expect("add abstract");
        idx.commit().expect("commit");

        let results = idx
            .search_with_predicate("rdf", "http://ex.org/title", 10)
            .expect("predicate search");
        let predicates: Vec<&str> = results.iter().map(|r| r.predicate.as_str()).collect();
        for p in predicates {
            assert_eq!(
                p, "http://ex.org/title",
                "Only title predicate should match"
            );
        }
    }
}