Skip to main content

hermes_core/dsl/
schema.rs

1//! Schema definitions for documents and fields
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// Field identifier
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub struct Field(pub u32);
9
10/// Types of fields supported
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub enum FieldType {
13    /// Text field - tokenized and indexed
14    #[serde(rename = "text")]
15    Text,
16    /// Unsigned 64-bit integer
17    #[serde(rename = "u64")]
18    U64,
19    /// Signed 64-bit integer
20    #[serde(rename = "i64")]
21    I64,
22    /// 64-bit floating point
23    #[serde(rename = "f64")]
24    F64,
25    /// Raw bytes (not tokenized)
26    #[serde(rename = "bytes")]
27    Bytes,
28    /// Sparse vector field - indexed as inverted posting lists with quantized weights
29    #[serde(rename = "sparse_vector")]
30    SparseVector,
31    /// Dense vector field - indexed using RaBitQ binary quantization for ANN search
32    #[serde(rename = "dense_vector")]
33    DenseVector,
34    /// JSON field - arbitrary JSON data, stored but not indexed
35    #[serde(rename = "json")]
36    Json,
37    /// Binary dense vector field - packed-bit storage with Hamming distance scoring
38    #[serde(rename = "binary_dense_vector")]
39    BinaryDenseVector,
40}
41
42/// Field options
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct FieldEntry {
45    pub name: String,
46    pub field_type: FieldType,
47    pub indexed: bool,
48    pub stored: bool,
49    /// Name of the tokenizer to use for this field (for text fields)
50    pub tokenizer: Option<String>,
51    /// Whether this field can have multiple values (serialized as array in JSON)
52    #[serde(default)]
53    pub multi: bool,
54    /// Position tracking mode for phrase queries and multi-field element tracking
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub positions: Option<PositionMode>,
57    /// Configuration for sparse vector fields (index size, weight quantization)
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub sparse_vector_config: Option<crate::structures::SparseVectorConfig>,
60    /// Configuration for dense vector fields (dimension, quantization)
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub dense_vector_config: Option<DenseVectorConfig>,
63    /// Configuration for binary dense vector fields (dimension in bits)
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub binary_dense_vector_config: Option<BinaryDenseVectorConfig>,
66    /// Whether this field has columnar fast-field storage for O(1) doc→value access.
67    /// Valid for u64, i64, f64, and text fields.
68    #[serde(default)]
69    pub fast: bool,
70    /// Whether this field is a primary key (unique constraint, at most one per schema)
71    #[serde(default)]
72    pub primary_key: bool,
73    /// Whether build-time document reordering (Recursive Graph Bisection) is enabled.
74    /// Valid for sparse_vector fields with BMP format. Clusters similar documents
75    /// into the same blocks for better pruning effectiveness.
76    #[serde(default)]
77    pub reorder: bool,
78}
79
80/// Position tracking mode for text fields
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub enum PositionMode {
84    /// Track only element ordinal for multi-valued fields (which array element)
85    /// Useful for returning which element matched without full phrase query support
86    Ordinal,
87    /// Track only token position within text (for phrase queries)
88    /// Does not track element ordinal - all positions are relative to concatenated text
89    TokenPosition,
90    /// Track both element ordinal and token position (full support)
91    /// Position format: (element_ordinal << 20) | token_position
92    Full,
93}
94
95impl PositionMode {
96    /// Whether this mode tracks element ordinals
97    pub fn tracks_ordinal(&self) -> bool {
98        matches!(self, PositionMode::Ordinal | PositionMode::Full)
99    }
100
101    /// Whether this mode tracks token positions
102    pub fn tracks_token_position(&self) -> bool {
103        matches!(self, PositionMode::TokenPosition | PositionMode::Full)
104    }
105}
106
107/// Vector index algorithm type
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum VectorIndexType {
111    /// Flat - brute-force search over raw vectors (accumulating state)
112    Flat,
113    /// RaBitQ - binary quantization, good for small datasets (<100K)
114    #[default]
115    RaBitQ,
116    /// IVF-RaBitQ - inverted file with RaBitQ, good for medium datasets
117    IvfRaBitQ,
118    /// ScaNN - product quantization with OPQ and anisotropic loss, best for large datasets
119    ScaNN,
120}
121
122/// Storage quantization for dense vector elements
123///
124/// Controls the precision of each vector coordinate in `.vectors` files.
125/// Lower precision reduces storage and memory bandwidth; scoring uses
126/// native-precision SIMD (no dequantization on the hot path).
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
128#[serde(rename_all = "snake_case")]
129pub enum DenseVectorQuantization {
130    /// 32-bit IEEE 754 float (4 bytes/dim) — full precision, baseline
131    #[default]
132    F32,
133    /// 16-bit IEEE 754 half-float (2 bytes/dim) — <0.1% recall loss for normalized embeddings
134    F16,
135    /// 8-bit unsigned scalar quantization (1 byte/dim) — maps [-1,1] → [0,255]
136    UInt8,
137    /// Binary packed-bit storage (1 bit per dimension, ceil(dim/8) bytes per vector).
138    /// Used internally by BinaryDenseVector fields. Not selectable for DenseVector fields.
139    Binary,
140}
141
142impl DenseVectorQuantization {
143    /// Bytes per element for non-binary quantization types.
144    /// Panics for Binary — use `dim.div_ceil(8)` for binary vector byte size.
145    pub fn element_size(self) -> usize {
146        match self {
147            Self::F32 => 4,
148            Self::F16 => 2,
149            Self::UInt8 => 1,
150            Self::Binary => panic!("element_size() not valid for Binary; use dim.div_ceil(8)"),
151        }
152    }
153
154    /// Wire format tag (stored in .vectors header)
155    pub fn tag(self) -> u8 {
156        match self {
157            Self::F32 => 0,
158            Self::F16 => 1,
159            Self::UInt8 => 2,
160            Self::Binary => 3,
161        }
162    }
163
164    /// Decode wire format tag
165    pub fn from_tag(tag: u8) -> Option<Self> {
166        match tag {
167            0 => Some(Self::F32),
168            1 => Some(Self::F16),
169            2 => Some(Self::UInt8),
170            3 => Some(Self::Binary),
171            _ => None,
172        }
173    }
174}
175
176/// Configuration for dense vector fields using Flat, RaBitQ, IVF-RaBitQ, or ScaNN
177///
178/// Indexes operate in two states:
179/// - **Flat (accumulating)**: Brute-force search over raw vectors. Used when vector count
180///   is below `build_threshold` or before `build_index` is called.
181/// - **Built (ANN)**: Fast approximate nearest neighbor search using trained structures.
182///   Centroids and codebooks are trained from data and stored within the segment.
183#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct DenseVectorConfig {
185    /// Dimensionality of vectors
186    pub dim: usize,
187    /// Target vector index algorithm (Flat, RaBitQ, IVF-RaBitQ, or ScaNN)
188    /// When in accumulating state, search uses brute-force regardless of this setting.
189    #[serde(default)]
190    pub index_type: VectorIndexType,
191    /// Storage quantization for vector elements (f32, f16, uint8)
192    #[serde(default)]
193    pub quantization: DenseVectorQuantization,
194    /// Number of IVF clusters for IVF-RaBitQ and ScaNN (default: sqrt(n) capped at 4096)
195    /// If None, automatically determined based on dataset size.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub num_clusters: Option<usize>,
198    /// Number of clusters to probe during search (default: 32)
199    #[serde(default = "default_nprobe")]
200    pub nprobe: usize,
201    /// Minimum number of vectors required before building ANN index.
202    /// Below this threshold, brute-force (Flat) search is used.
203    /// Default: 1000 for RaBitQ, 10000 for IVF-RaBitQ/ScaNN.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub build_threshold: Option<usize>,
206    /// Whether stored vectors are pre-normalized to unit L2 norm.
207    /// When true, scoring skips per-vector norm computation (cosine = dot / ||q||),
208    /// reducing compute by ~40%. Common for embedding models (e.g. OpenAI, Cohere).
209    /// Default: true (most embedding models produce L2-normalized vectors).
210    #[serde(default = "default_unit_norm")]
211    pub unit_norm: bool,
212    /// Total RaBitQ bits per dimension for IVF-RaBitQ indexes.
213    /// 1 = classic binary RaBitQ (default). 2-8 = extended multi-bit codes
214    /// with much tighter distance estimates — allows lowering rerank_factor
215    /// (fewer raw-vector reads) at the same recall. Recommended: 4-5 for
216    /// disk-resident indexes.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub rabitq_bits: Option<u8>,
219    /// SOAR spilled cluster assignments for IVF-based indexes (IVF-RaBitQ, ScaNN).
220    /// Assigns vectors to a secondary cluster with an orthogonality-amplified
221    /// residual, improving recall at the same nprobe for ~1.2-2x assignment storage.
222    /// Default: None (disabled). Ignored for Flat/RaBitQ index types.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub soar: Option<crate::structures::SoarConfig>,
225}
226
227fn default_nprobe() -> usize {
228    32
229}
230
231fn default_unit_norm() -> bool {
232    true
233}
234
235impl DenseVectorConfig {
236    pub fn new(dim: usize) -> Self {
237        Self {
238            dim,
239            index_type: VectorIndexType::RaBitQ,
240            quantization: DenseVectorQuantization::F32,
241            num_clusters: None,
242            nprobe: 32,
243            build_threshold: None,
244            unit_norm: true,
245            soar: None,
246            rabitq_bits: None,
247        }
248    }
249
250    /// Create IVF-RaBitQ configuration
251    pub fn with_ivf(dim: usize, num_clusters: Option<usize>, nprobe: usize) -> Self {
252        Self {
253            dim,
254            index_type: VectorIndexType::IvfRaBitQ,
255            quantization: DenseVectorQuantization::F32,
256            num_clusters,
257            nprobe,
258            build_threshold: None,
259            unit_norm: true,
260            soar: None,
261            rabitq_bits: None,
262        }
263    }
264
265    /// Create ScaNN configuration
266    pub fn with_scann(dim: usize, num_clusters: Option<usize>, nprobe: usize) -> Self {
267        Self {
268            dim,
269            index_type: VectorIndexType::ScaNN,
270            quantization: DenseVectorQuantization::F32,
271            num_clusters,
272            nprobe,
273            build_threshold: None,
274            unit_norm: true,
275            soar: None,
276            rabitq_bits: None,
277        }
278    }
279
280    /// Create Flat (brute-force) configuration - no ANN index
281    pub fn flat(dim: usize) -> Self {
282        Self {
283            dim,
284            index_type: VectorIndexType::Flat,
285            quantization: DenseVectorQuantization::F32,
286            num_clusters: None,
287            nprobe: 0,
288            build_threshold: None,
289            unit_norm: true,
290            soar: None,
291            rabitq_bits: None,
292        }
293    }
294
295    /// Set storage quantization
296    pub fn with_quantization(mut self, quantization: DenseVectorQuantization) -> Self {
297        self.quantization = quantization;
298        self
299    }
300
301    /// Set build threshold for auto-building ANN index
302    pub fn with_build_threshold(mut self, threshold: usize) -> Self {
303        self.build_threshold = Some(threshold);
304        self
305    }
306
307    /// Mark vectors as pre-normalized to unit L2 norm
308    pub fn with_unit_norm(mut self) -> Self {
309        self.unit_norm = true;
310        self
311    }
312
313    /// Set number of IVF clusters
314    pub fn with_num_clusters(mut self, num_clusters: usize) -> Self {
315        self.num_clusters = Some(num_clusters);
316        self
317    }
318
319    /// Set RaBitQ total bits per dimension (1 = classic, 2-8 = extended)
320    pub fn with_rabitq_bits(mut self, bits: u8) -> Self {
321        self.rabitq_bits = Some(bits.clamp(1, 8));
322        self
323    }
324
325    /// Enable SOAR spilled secondary cluster assignments (IVF-based indexes only)
326    pub fn with_soar(mut self, soar: crate::structures::SoarConfig) -> Self {
327        self.soar = Some(soar);
328        self
329    }
330
331    /// Check if this config uses IVF
332    pub fn uses_ivf(&self) -> bool {
333        matches!(
334            self.index_type,
335            VectorIndexType::IvfRaBitQ | VectorIndexType::ScaNN
336        )
337    }
338
339    /// Check if this config uses ScaNN
340    pub fn uses_scann(&self) -> bool {
341        self.index_type == VectorIndexType::ScaNN
342    }
343
344    /// Check if this config is flat (brute-force)
345    pub fn is_flat(&self) -> bool {
346        self.index_type == VectorIndexType::Flat
347    }
348
349    /// Get the default build threshold for this index type
350    pub fn default_build_threshold(&self) -> usize {
351        self.build_threshold.unwrap_or(match self.index_type {
352            VectorIndexType::Flat => usize::MAX, // Never auto-build
353            VectorIndexType::RaBitQ => 1000,
354            VectorIndexType::IvfRaBitQ | VectorIndexType::ScaNN => 10000,
355        })
356    }
357
358    /// Calculate optimal number of clusters for given vector count
359    pub fn optimal_num_clusters(&self, num_vectors: usize) -> usize {
360        self.num_clusters.unwrap_or_else(|| {
361            // sqrt(n) heuristic, capped at 4096
362            let optimal = (num_vectors as f64).sqrt() as usize;
363            optimal.clamp(16, 4096)
364        })
365    }
366}
367
368/// Configuration for binary dense vector fields
369///
370/// Binary dense vectors store packed bits (1 bit per dimension) and use
371/// Hamming distance for scoring. Always uses brute-force flat search
372/// (Hamming popcount is ~10ns/vec for 768-bit, ANN indexes don't help).
373#[derive(Debug, Clone, Serialize, Deserialize)]
374pub struct BinaryDenseVectorConfig {
375    /// Number of bits (dimensions). Storage is ceil(dim/8) bytes per vector.
376    pub dim: usize,
377    /// ANN index type: Flat (brute-force SIMD Hamming, default) or Ivf
378    /// (k-majority Hamming clusters — probe `nprobe` clusters at query time).
379    /// IVF pays off for segments past a few million vectors.
380    #[serde(default)]
381    pub index_type: BinaryIndexType,
382    /// Number of IVF clusters (default: sqrt(n) capped at 4096)
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub num_clusters: Option<usize>,
385    /// Clusters to probe during search (default: 32)
386    #[serde(default = "default_nprobe")]
387    pub nprobe: usize,
388    /// Minimum vectors before building the IVF index (default: 100_000 —
389    /// below that brute-force SIMD Hamming is faster than probing).
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub build_threshold: Option<usize>,
392}
393
394/// ANN index type for binary dense vector fields
395#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
396#[serde(rename_all = "snake_case")]
397pub enum BinaryIndexType {
398    /// Brute-force SIMD Hamming scan (default)
399    #[default]
400    Flat,
401    /// IVF with k-majority Hamming clustering
402    Ivf,
403}
404
405impl BinaryDenseVectorConfig {
406    pub fn new(dim: usize) -> Self {
407        assert!(
408            dim.is_multiple_of(8),
409            "BinaryDenseVector dimension must be a multiple of 8, got {dim}"
410        );
411        Self {
412            dim,
413            index_type: BinaryIndexType::Flat,
414            num_clusters: None,
415            nprobe: 32,
416            build_threshold: None,
417        }
418    }
419
420    /// Enable the IVF index (builder pattern)
421    pub fn with_ivf(mut self, num_clusters: Option<usize>, nprobe: usize) -> Self {
422        self.index_type = BinaryIndexType::Ivf;
423        self.num_clusters = num_clusters;
424        self.nprobe = nprobe;
425        self
426    }
427
428    /// Set the build threshold (builder pattern)
429    pub fn with_build_threshold(mut self, threshold: usize) -> Self {
430        self.build_threshold = Some(threshold);
431        self
432    }
433
434    /// Default build threshold: brute-force wins below ~100K vectors.
435    pub fn default_build_threshold(&self) -> usize {
436        self.build_threshold.unwrap_or(100_000)
437    }
438
439    /// Optimal cluster count for a given vector count (sqrt(n), capped)
440    pub fn optimal_num_clusters(&self, num_vectors: usize) -> usize {
441        self.num_clusters.unwrap_or_else(|| {
442            let optimal = (num_vectors as f64).sqrt() as usize;
443            optimal.clamp(16, 4096)
444        })
445    }
446
447    /// Number of bytes needed to store one vector
448    pub fn byte_len(&self) -> usize {
449        self.dim.div_ceil(8)
450    }
451}
452
453use super::query_field_router::QueryRouterRule;
454
455/// Schema defining document structure
456#[derive(Debug, Clone, Default, Serialize, Deserialize)]
457pub struct Schema {
458    fields: Vec<FieldEntry>,
459    name_to_field: HashMap<String, Field>,
460    /// Default fields for query parsing (when no field is specified)
461    #[serde(default)]
462    default_fields: Vec<Field>,
463    /// Query router rules for routing queries to specific fields based on regex patterns
464    #[serde(default)]
465    query_routers: Vec<QueryRouterRule>,
466    /// Run BP (graph bisection) reordering of `reorder`-attributed BMP fields
467    /// inside segment merges. SDL: `reorder_on_merge: true` at index level.
468    /// Absent = disabled (merges block-copy; the standalone reorder pass
469    /// handles ordering).
470    #[serde(default)]
471    reorder_on_merge: bool,
472}
473
474impl Schema {
475    pub fn builder() -> SchemaBuilder {
476        SchemaBuilder::default()
477    }
478
479    pub fn get_field(&self, name: &str) -> Option<Field> {
480        self.name_to_field.get(name).copied()
481    }
482
483    pub fn get_field_entry(&self, field: Field) -> Option<&FieldEntry> {
484        self.fields.get(field.0 as usize)
485    }
486
487    pub fn get_field_name(&self, field: Field) -> Option<&str> {
488        self.fields.get(field.0 as usize).map(|e| e.name.as_str())
489    }
490
491    pub fn fields(&self) -> impl Iterator<Item = (Field, &FieldEntry)> {
492        self.fields
493            .iter()
494            .enumerate()
495            .map(|(i, e)| (Field(i as u32), e))
496    }
497
498    pub fn num_fields(&self) -> usize {
499        self.fields.len()
500    }
501
502    /// Whether any field has the `reorder` attribute set.
503    /// Used by the background optimizer to determine which indexes need BP reordering.
504    pub fn has_reorder_fields(&self) -> bool {
505        self.fields.iter().any(|e| e.reorder)
506    }
507
508    /// Whether merges BP-reorder `reorder`-attributed BMP fields while writing
509    /// the merged segment (index-level SDL option `reorder_on_merge: true`).
510    pub fn reorder_on_merge(&self) -> bool {
511        self.reorder_on_merge
512    }
513
514    /// Get the default fields for query parsing
515    pub fn default_fields(&self) -> &[Field] {
516        &self.default_fields
517    }
518
519    /// Set default fields (used by builder)
520    pub fn set_default_fields(&mut self, fields: Vec<Field>) {
521        self.default_fields = fields;
522    }
523
524    /// Get the query router rules
525    pub fn query_routers(&self) -> &[QueryRouterRule] {
526        &self.query_routers
527    }
528
529    /// Set query router rules
530    pub fn set_query_routers(&mut self, rules: Vec<QueryRouterRule>) {
531        self.query_routers = rules;
532    }
533
534    /// Get the primary key field, if one is defined
535    pub fn primary_field(&self) -> Option<Field> {
536        self.fields
537            .iter()
538            .enumerate()
539            .find(|(_, e)| e.primary_key)
540            .map(|(i, _)| Field(i as u32))
541    }
542}
543
544/// Builder for Schema
545#[derive(Debug, Default)]
546pub struct SchemaBuilder {
547    fields: Vec<FieldEntry>,
548    default_fields: Vec<String>,
549    query_routers: Vec<QueryRouterRule>,
550    reorder_on_merge: bool,
551}
552
553impl SchemaBuilder {
554    pub fn add_text_field(&mut self, name: &str, indexed: bool, stored: bool) -> Field {
555        self.add_field_with_tokenizer(
556            name,
557            FieldType::Text,
558            indexed,
559            stored,
560            Some("simple".to_string()),
561        )
562    }
563
564    pub fn add_text_field_with_tokenizer(
565        &mut self,
566        name: &str,
567        indexed: bool,
568        stored: bool,
569        tokenizer: &str,
570    ) -> Field {
571        self.add_field_with_tokenizer(
572            name,
573            FieldType::Text,
574            indexed,
575            stored,
576            Some(tokenizer.to_string()),
577        )
578    }
579
580    pub fn add_u64_field(&mut self, name: &str, indexed: bool, stored: bool) -> Field {
581        self.add_field(name, FieldType::U64, indexed, stored)
582    }
583
584    pub fn add_i64_field(&mut self, name: &str, indexed: bool, stored: bool) -> Field {
585        self.add_field(name, FieldType::I64, indexed, stored)
586    }
587
588    pub fn add_f64_field(&mut self, name: &str, indexed: bool, stored: bool) -> Field {
589        self.add_field(name, FieldType::F64, indexed, stored)
590    }
591
592    pub fn add_bytes_field(&mut self, name: &str, stored: bool) -> Field {
593        self.add_field(name, FieldType::Bytes, false, stored)
594    }
595
596    /// Add a JSON field for storing arbitrary JSON data
597    ///
598    /// JSON fields are never indexed, only stored. They can hold any valid JSON value
599    /// (objects, arrays, strings, numbers, booleans, null).
600    pub fn add_json_field(&mut self, name: &str, stored: bool) -> Field {
601        self.add_field(name, FieldType::Json, false, stored)
602    }
603
604    /// Add a sparse vector field with default configuration
605    ///
606    /// Sparse vectors are indexed as inverted posting lists where each dimension
607    /// becomes a "term" and documents have quantized weights for each dimension.
608    pub fn add_sparse_vector_field(&mut self, name: &str, indexed: bool, stored: bool) -> Field {
609        self.add_sparse_vector_field_with_config(
610            name,
611            indexed,
612            stored,
613            crate::structures::SparseVectorConfig::default(),
614        )
615    }
616
617    /// Add a sparse vector field with custom configuration
618    ///
619    /// Use `SparseVectorConfig::splade()` for SPLADE models (u16 indices, uint8 weights).
620    /// Use `SparseVectorConfig::compact()` for maximum compression (u16 indices, uint4 weights).
621    pub fn add_sparse_vector_field_with_config(
622        &mut self,
623        name: &str,
624        indexed: bool,
625        stored: bool,
626        config: crate::structures::SparseVectorConfig,
627    ) -> Field {
628        let field = Field(self.fields.len() as u32);
629        self.fields.push(FieldEntry {
630            name: name.to_string(),
631            field_type: FieldType::SparseVector,
632            indexed,
633            stored,
634            tokenizer: None,
635            multi: false,
636            positions: None,
637            sparse_vector_config: Some(config),
638            dense_vector_config: None,
639            binary_dense_vector_config: None,
640            fast: false,
641            primary_key: false,
642            reorder: false,
643        });
644        field
645    }
646
647    /// Set sparse vector configuration for an existing field
648    pub fn set_sparse_vector_config(
649        &mut self,
650        field: Field,
651        config: crate::structures::SparseVectorConfig,
652    ) {
653        if let Some(entry) = self.fields.get_mut(field.0 as usize) {
654            entry.sparse_vector_config = Some(config);
655        }
656    }
657
658    /// Add a dense vector field with default configuration
659    ///
660    /// Dense vectors are indexed using RaBitQ binary quantization for fast ANN search.
661    /// The dimension must be specified as it determines the quantization structure.
662    pub fn add_dense_vector_field(
663        &mut self,
664        name: &str,
665        dim: usize,
666        indexed: bool,
667        stored: bool,
668    ) -> Field {
669        self.add_dense_vector_field_with_config(name, indexed, stored, DenseVectorConfig::new(dim))
670    }
671
672    /// Add a dense vector field with custom configuration
673    pub fn add_dense_vector_field_with_config(
674        &mut self,
675        name: &str,
676        indexed: bool,
677        stored: bool,
678        config: DenseVectorConfig,
679    ) -> Field {
680        let field = Field(self.fields.len() as u32);
681        self.fields.push(FieldEntry {
682            name: name.to_string(),
683            field_type: FieldType::DenseVector,
684            indexed,
685            stored,
686            tokenizer: None,
687            multi: false,
688            positions: None,
689            sparse_vector_config: None,
690            dense_vector_config: Some(config),
691            binary_dense_vector_config: None,
692            fast: false,
693            primary_key: false,
694            reorder: false,
695        });
696        field
697    }
698
699    /// Add a binary dense vector field
700    ///
701    /// Binary dense vectors use packed-bit storage (1 bit per dimension)
702    /// and Hamming distance scoring. Always brute-force flat search.
703    pub fn add_binary_dense_vector_field(
704        &mut self,
705        name: &str,
706        dim: usize,
707        indexed: bool,
708        stored: bool,
709    ) -> Field {
710        self.add_binary_dense_vector_field_with_config(
711            name,
712            indexed,
713            stored,
714            BinaryDenseVectorConfig::new(dim),
715        )
716    }
717
718    /// Add a binary dense vector field with custom configuration
719    pub fn add_binary_dense_vector_field_with_config(
720        &mut self,
721        name: &str,
722        indexed: bool,
723        stored: bool,
724        config: BinaryDenseVectorConfig,
725    ) -> Field {
726        let field = Field(self.fields.len() as u32);
727        self.fields.push(FieldEntry {
728            name: name.to_string(),
729            field_type: FieldType::BinaryDenseVector,
730            indexed,
731            stored,
732            tokenizer: None,
733            multi: false,
734            positions: None,
735            sparse_vector_config: None,
736            dense_vector_config: None,
737            binary_dense_vector_config: Some(config),
738            fast: false,
739            primary_key: false,
740            reorder: false,
741        });
742        field
743    }
744
745    fn add_field(
746        &mut self,
747        name: &str,
748        field_type: FieldType,
749        indexed: bool,
750        stored: bool,
751    ) -> Field {
752        self.add_field_with_tokenizer(name, field_type, indexed, stored, None)
753    }
754
755    fn add_field_with_tokenizer(
756        &mut self,
757        name: &str,
758        field_type: FieldType,
759        indexed: bool,
760        stored: bool,
761        tokenizer: Option<String>,
762    ) -> Field {
763        self.add_field_full(name, field_type, indexed, stored, tokenizer, false)
764    }
765
766    fn add_field_full(
767        &mut self,
768        name: &str,
769        field_type: FieldType,
770        indexed: bool,
771        stored: bool,
772        tokenizer: Option<String>,
773        multi: bool,
774    ) -> Field {
775        let field = Field(self.fields.len() as u32);
776        self.fields.push(FieldEntry {
777            name: name.to_string(),
778            field_type,
779            indexed,
780            stored,
781            tokenizer,
782            multi,
783            positions: None,
784            sparse_vector_config: None,
785            dense_vector_config: None,
786            binary_dense_vector_config: None,
787            fast: false,
788            primary_key: false,
789            reorder: false,
790        });
791        field
792    }
793
794    /// Set the multi attribute on the last added field
795    pub fn set_multi(&mut self, field: Field, multi: bool) {
796        if let Some(entry) = self.fields.get_mut(field.0 as usize) {
797            entry.multi = multi;
798        }
799    }
800
801    /// Set fast-field columnar storage for O(1) doc→value access.
802    /// Valid for u64, i64, f64, and text fields.
803    pub fn set_fast(&mut self, field: Field, fast: bool) {
804        if let Some(entry) = self.fields.get_mut(field.0 as usize) {
805            entry.fast = fast;
806        }
807    }
808
809    /// Mark a field as the primary key (unique constraint)
810    pub fn set_primary_key(&mut self, field: Field) {
811        if let Some(entry) = self.fields.get_mut(field.0 as usize) {
812            entry.primary_key = true;
813        }
814    }
815
816    /// Enable build-time document reordering (Recursive Graph Bisection) for BMP fields
817    pub fn set_reorder(&mut self, field: Field, reorder: bool) {
818        if let Some(entry) = self.fields.get_mut(field.0 as usize) {
819            entry.reorder = reorder;
820        }
821    }
822
823    /// Enable BP reordering of `reorder`-attributed BMP fields inside merges
824    /// (index-level; SDL `reorder_on_merge: true`). Default: disabled.
825    pub fn set_reorder_on_merge(&mut self, on: bool) {
826        self.reorder_on_merge = on;
827    }
828
829    /// Set position tracking mode for phrase queries and multi-field element tracking
830    pub fn set_positions(&mut self, field: Field, mode: PositionMode) {
831        if let Some(entry) = self.fields.get_mut(field.0 as usize) {
832            entry.positions = Some(mode);
833        }
834    }
835
836    /// Set default fields by name
837    pub fn set_default_fields(&mut self, field_names: Vec<String>) {
838        self.default_fields = field_names;
839    }
840
841    /// Set query router rules
842    pub fn set_query_routers(&mut self, rules: Vec<QueryRouterRule>) {
843        self.query_routers = rules;
844    }
845
846    pub fn build(self) -> Schema {
847        let mut name_to_field = HashMap::new();
848        for (i, entry) in self.fields.iter().enumerate() {
849            name_to_field.insert(entry.name.clone(), Field(i as u32));
850        }
851
852        // Resolve default field names to Field IDs
853        let default_fields: Vec<Field> = self
854            .default_fields
855            .iter()
856            .filter_map(|name| name_to_field.get(name).copied())
857            .collect();
858
859        Schema {
860            fields: self.fields,
861            name_to_field,
862            default_fields,
863            query_routers: self.query_routers,
864            reorder_on_merge: self.reorder_on_merge,
865        }
866    }
867}
868
869/// Value that can be stored in a field
870#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
871pub enum FieldValue {
872    #[serde(rename = "text")]
873    Text(String),
874    #[serde(rename = "u64")]
875    U64(u64),
876    #[serde(rename = "i64")]
877    I64(i64),
878    #[serde(rename = "f64")]
879    F64(f64),
880    #[serde(rename = "bytes")]
881    Bytes(Vec<u8>),
882    /// Sparse vector: list of (dimension_id, weight) pairs
883    #[serde(rename = "sparse_vector")]
884    SparseVector(Vec<(u32, f32)>),
885    /// Dense vector: float32 values
886    #[serde(rename = "dense_vector")]
887    DenseVector(Vec<f32>),
888    /// Arbitrary JSON value
889    #[serde(rename = "json")]
890    Json(serde_json::Value),
891    /// Binary dense vector: packed bits (ceil(dim/8) bytes)
892    #[serde(rename = "binary_dense_vector")]
893    BinaryDenseVector(Vec<u8>),
894}
895
896impl FieldValue {
897    pub fn as_text(&self) -> Option<&str> {
898        match self {
899            FieldValue::Text(s) => Some(s),
900            _ => None,
901        }
902    }
903
904    pub fn as_u64(&self) -> Option<u64> {
905        match self {
906            FieldValue::U64(v) => Some(*v),
907            _ => None,
908        }
909    }
910
911    pub fn as_i64(&self) -> Option<i64> {
912        match self {
913            FieldValue::I64(v) => Some(*v),
914            _ => None,
915        }
916    }
917
918    pub fn as_f64(&self) -> Option<f64> {
919        match self {
920            FieldValue::F64(v) => Some(*v),
921            _ => None,
922        }
923    }
924
925    pub fn as_bytes(&self) -> Option<&[u8]> {
926        match self {
927            FieldValue::Bytes(b) => Some(b),
928            _ => None,
929        }
930    }
931
932    pub fn as_sparse_vector(&self) -> Option<&[(u32, f32)]> {
933        match self {
934            FieldValue::SparseVector(entries) => Some(entries),
935            _ => None,
936        }
937    }
938
939    pub fn as_dense_vector(&self) -> Option<&[f32]> {
940        match self {
941            FieldValue::DenseVector(v) => Some(v),
942            _ => None,
943        }
944    }
945
946    pub fn as_json(&self) -> Option<&serde_json::Value> {
947        match self {
948            FieldValue::Json(v) => Some(v),
949            _ => None,
950        }
951    }
952
953    pub fn as_binary_dense_vector(&self) -> Option<&[u8]> {
954        match self {
955            FieldValue::BinaryDenseVector(v) => Some(v),
956            _ => None,
957        }
958    }
959}
960
961/// A document to be indexed
962#[derive(Debug, Clone, Default, Serialize, Deserialize)]
963pub struct Document {
964    field_values: Vec<(Field, FieldValue)>,
965}
966
967impl Document {
968    pub fn new() -> Self {
969        Self::default()
970    }
971
972    pub fn add_text(&mut self, field: Field, value: impl Into<String>) {
973        self.field_values
974            .push((field, FieldValue::Text(value.into())));
975    }
976
977    pub fn add_u64(&mut self, field: Field, value: u64) {
978        self.field_values.push((field, FieldValue::U64(value)));
979    }
980
981    pub fn add_i64(&mut self, field: Field, value: i64) {
982        self.field_values.push((field, FieldValue::I64(value)));
983    }
984
985    pub fn add_f64(&mut self, field: Field, value: f64) {
986        self.field_values.push((field, FieldValue::F64(value)));
987    }
988
989    pub fn add_bytes(&mut self, field: Field, value: Vec<u8>) {
990        self.field_values.push((field, FieldValue::Bytes(value)));
991    }
992
993    pub fn add_sparse_vector(&mut self, field: Field, entries: Vec<(u32, f32)>) {
994        self.field_values
995            .push((field, FieldValue::SparseVector(entries)));
996    }
997
998    pub fn add_dense_vector(&mut self, field: Field, values: Vec<f32>) {
999        self.field_values
1000            .push((field, FieldValue::DenseVector(values)));
1001    }
1002
1003    pub fn add_json(&mut self, field: Field, value: serde_json::Value) {
1004        self.field_values.push((field, FieldValue::Json(value)));
1005    }
1006
1007    pub fn add_binary_dense_vector(&mut self, field: Field, values: Vec<u8>) {
1008        self.field_values
1009            .push((field, FieldValue::BinaryDenseVector(values)));
1010    }
1011
1012    pub fn get_first(&self, field: Field) -> Option<&FieldValue> {
1013        self.field_values
1014            .iter()
1015            .find(|(f, _)| *f == field)
1016            .map(|(_, v)| v)
1017    }
1018
1019    pub fn get_all(&self, field: Field) -> impl Iterator<Item = &FieldValue> {
1020        self.field_values
1021            .iter()
1022            .filter(move |(f, _)| *f == field)
1023            .map(|(_, v)| v)
1024    }
1025
1026    pub fn field_values(&self) -> &[(Field, FieldValue)] {
1027        &self.field_values
1028    }
1029
1030    /// Return a new Document containing only fields marked as `stored` in the schema
1031    pub fn filter_stored(&self, schema: &Schema) -> Document {
1032        Document {
1033            field_values: self
1034                .field_values
1035                .iter()
1036                .filter(|(field, _)| {
1037                    schema
1038                        .get_field_entry(*field)
1039                        .is_some_and(|entry| entry.stored)
1040                })
1041                .cloned()
1042                .collect(),
1043        }
1044    }
1045
1046    /// Convert document to a JSON object using field names from schema
1047    ///
1048    /// Fields marked as `multi` in the schema are always returned as JSON arrays.
1049    /// Other fields with multiple values are also returned as arrays.
1050    /// Fields with a single value (and not marked multi) are returned as scalar values.
1051    pub fn to_json(&self, schema: &Schema) -> serde_json::Value {
1052        use std::collections::HashMap;
1053
1054        // Group values by field, keeping track of field entry for multi check
1055        let mut field_values_map: HashMap<Field, (String, bool, Vec<serde_json::Value>)> =
1056            HashMap::new();
1057
1058        for (field, value) in &self.field_values {
1059            if let Some(entry) = schema.get_field_entry(*field) {
1060                let json_value = match value {
1061                    FieldValue::Text(s) => serde_json::Value::String(s.clone()),
1062                    FieldValue::U64(n) => serde_json::Value::Number((*n).into()),
1063                    FieldValue::I64(n) => serde_json::Value::Number((*n).into()),
1064                    FieldValue::F64(n) => serde_json::json!(n),
1065                    FieldValue::Bytes(b) => {
1066                        use base64::Engine;
1067                        serde_json::Value::String(
1068                            base64::engine::general_purpose::STANDARD.encode(b),
1069                        )
1070                    }
1071                    FieldValue::SparseVector(entries) => {
1072                        let indices: Vec<u32> = entries.iter().map(|(i, _)| *i).collect();
1073                        let values: Vec<f32> = entries.iter().map(|(_, v)| *v).collect();
1074                        serde_json::json!({
1075                            "indices": indices,
1076                            "values": values
1077                        })
1078                    }
1079                    FieldValue::DenseVector(values) => {
1080                        serde_json::json!(values)
1081                    }
1082                    FieldValue::Json(v) => v.clone(),
1083                    FieldValue::BinaryDenseVector(b) => {
1084                        use base64::Engine;
1085                        serde_json::Value::String(
1086                            base64::engine::general_purpose::STANDARD.encode(b),
1087                        )
1088                    }
1089                };
1090                field_values_map
1091                    .entry(*field)
1092                    .or_insert_with(|| (entry.name.clone(), entry.multi, Vec::new()))
1093                    .2
1094                    .push(json_value);
1095            }
1096        }
1097
1098        // Convert to JSON object, using arrays for multi fields or when multiple values exist
1099        let mut map = serde_json::Map::new();
1100        for (_field, (name, is_multi, values)) in field_values_map {
1101            let json_value = if is_multi || values.len() > 1 {
1102                serde_json::Value::Array(values)
1103            } else {
1104                values.into_iter().next().unwrap()
1105            };
1106            map.insert(name, json_value);
1107        }
1108
1109        serde_json::Value::Object(map)
1110    }
1111
1112    /// Create a Document from a JSON object using field names from schema
1113    ///
1114    /// Supports:
1115    /// - String values -> Text fields
1116    /// - Number values -> U64/I64/F64 fields (based on schema type)
1117    /// - Array values -> Multiple values for the same field (multifields)
1118    ///
1119    /// Unknown fields (not in schema) are silently ignored.
1120    pub fn from_json(json: &serde_json::Value, schema: &Schema) -> Option<Self> {
1121        let obj = json.as_object()?;
1122        let mut doc = Document::new();
1123
1124        for (key, value) in obj {
1125            if let Some(field) = schema.get_field(key) {
1126                let field_entry = schema.get_field_entry(field)?;
1127                Self::add_json_value(&mut doc, field, &field_entry.field_type, value);
1128            }
1129        }
1130
1131        Some(doc)
1132    }
1133
1134    /// Helper to add a JSON value to a document, handling type conversion
1135    fn add_json_value(
1136        doc: &mut Document,
1137        field: Field,
1138        field_type: &FieldType,
1139        value: &serde_json::Value,
1140    ) {
1141        match value {
1142            serde_json::Value::String(s) => {
1143                if matches!(field_type, FieldType::Text) {
1144                    doc.add_text(field, s.clone());
1145                }
1146            }
1147            serde_json::Value::Number(n) => {
1148                match field_type {
1149                    FieldType::I64 => {
1150                        if let Some(i) = n.as_i64() {
1151                            doc.add_i64(field, i);
1152                        }
1153                    }
1154                    FieldType::U64 => {
1155                        if let Some(u) = n.as_u64() {
1156                            doc.add_u64(field, u);
1157                        } else if let Some(i) = n.as_i64() {
1158                            // Allow positive i64 as u64
1159                            if i >= 0 {
1160                                doc.add_u64(field, i as u64);
1161                            }
1162                        }
1163                    }
1164                    FieldType::F64 => {
1165                        if let Some(f) = n.as_f64() {
1166                            doc.add_f64(field, f);
1167                        }
1168                    }
1169                    _ => {}
1170                }
1171            }
1172            // Handle arrays (multifields) - add each element separately
1173            serde_json::Value::Array(arr) => {
1174                for item in arr {
1175                    Self::add_json_value(doc, field, field_type, item);
1176                }
1177            }
1178            // Handle sparse vector objects
1179            serde_json::Value::Object(obj) if matches!(field_type, FieldType::SparseVector) => {
1180                if let (Some(indices_val), Some(values_val)) =
1181                    (obj.get("indices"), obj.get("values"))
1182                {
1183                    let indices: Vec<u32> = indices_val
1184                        .as_array()
1185                        .map(|arr| {
1186                            arr.iter()
1187                                .filter_map(|v| v.as_u64().map(|n| n as u32))
1188                                .collect()
1189                        })
1190                        .unwrap_or_default();
1191                    let values: Vec<f32> = values_val
1192                        .as_array()
1193                        .map(|arr| {
1194                            arr.iter()
1195                                .filter_map(|v| v.as_f64().map(|n| n as f32))
1196                                .collect()
1197                        })
1198                        .unwrap_or_default();
1199                    if indices.len() == values.len() {
1200                        let entries: Vec<(u32, f32)> = indices.into_iter().zip(values).collect();
1201                        doc.add_sparse_vector(field, entries);
1202                    }
1203                }
1204            }
1205            // Handle JSON fields - accept any value directly
1206            _ if matches!(field_type, FieldType::Json) => {
1207                doc.add_json(field, value.clone());
1208            }
1209            serde_json::Value::Object(_) => {}
1210            _ => {}
1211        }
1212    }
1213}
1214
1215#[cfg(test)]
1216mod tests {
1217    use super::*;
1218
1219    #[test]
1220    fn test_schema_builder() {
1221        let mut builder = Schema::builder();
1222        let title = builder.add_text_field("title", true, true);
1223        let body = builder.add_text_field("body", true, false);
1224        let count = builder.add_u64_field("count", true, true);
1225        let schema = builder.build();
1226
1227        assert_eq!(schema.get_field("title"), Some(title));
1228        assert_eq!(schema.get_field("body"), Some(body));
1229        assert_eq!(schema.get_field("count"), Some(count));
1230        assert_eq!(schema.get_field("nonexistent"), None);
1231    }
1232
1233    #[test]
1234    fn test_document() {
1235        let mut builder = Schema::builder();
1236        let title = builder.add_text_field("title", true, true);
1237        let count = builder.add_u64_field("count", true, true);
1238        let _schema = builder.build();
1239
1240        let mut doc = Document::new();
1241        doc.add_text(title, "Hello World");
1242        doc.add_u64(count, 42);
1243
1244        assert_eq!(doc.get_first(title).unwrap().as_text(), Some("Hello World"));
1245        assert_eq!(doc.get_first(count).unwrap().as_u64(), Some(42));
1246    }
1247
1248    #[test]
1249    fn test_document_serialization() {
1250        let mut builder = Schema::builder();
1251        let title = builder.add_text_field("title", true, true);
1252        let count = builder.add_u64_field("count", true, true);
1253        let _schema = builder.build();
1254
1255        let mut doc = Document::new();
1256        doc.add_text(title, "Hello World");
1257        doc.add_u64(count, 42);
1258
1259        // Serialize
1260        let json = serde_json::to_string(&doc).unwrap();
1261        println!("Serialized doc: {}", json);
1262
1263        // Deserialize
1264        let doc2: Document = serde_json::from_str(&json).unwrap();
1265        assert_eq!(
1266            doc2.field_values().len(),
1267            2,
1268            "Should have 2 field values after deserialization"
1269        );
1270        assert_eq!(
1271            doc2.get_first(title).unwrap().as_text(),
1272            Some("Hello World")
1273        );
1274        assert_eq!(doc2.get_first(count).unwrap().as_u64(), Some(42));
1275    }
1276
1277    #[test]
1278    fn test_multivalue_field() {
1279        let mut builder = Schema::builder();
1280        let uris = builder.add_text_field("uris", true, true);
1281        let title = builder.add_text_field("title", true, true);
1282        let schema = builder.build();
1283
1284        // Create document with multiple values for the same field
1285        let mut doc = Document::new();
1286        doc.add_text(uris, "one");
1287        doc.add_text(uris, "two");
1288        doc.add_text(title, "Test Document");
1289
1290        // Verify get_first returns the first value
1291        assert_eq!(doc.get_first(uris).unwrap().as_text(), Some("one"));
1292
1293        // Verify get_all returns all values
1294        let all_uris: Vec<_> = doc.get_all(uris).collect();
1295        assert_eq!(all_uris.len(), 2);
1296        assert_eq!(all_uris[0].as_text(), Some("one"));
1297        assert_eq!(all_uris[1].as_text(), Some("two"));
1298
1299        // Verify to_json returns array for multi-value field
1300        let json = doc.to_json(&schema);
1301        let uris_json = json.get("uris").unwrap();
1302        assert!(uris_json.is_array(), "Multi-value field should be an array");
1303        let uris_arr = uris_json.as_array().unwrap();
1304        assert_eq!(uris_arr.len(), 2);
1305        assert_eq!(uris_arr[0].as_str(), Some("one"));
1306        assert_eq!(uris_arr[1].as_str(), Some("two"));
1307
1308        // Verify single-value field is NOT an array
1309        let title_json = json.get("title").unwrap();
1310        assert!(
1311            title_json.is_string(),
1312            "Single-value field should be a string"
1313        );
1314        assert_eq!(title_json.as_str(), Some("Test Document"));
1315    }
1316
1317    #[test]
1318    fn test_multivalue_from_json() {
1319        let mut builder = Schema::builder();
1320        let uris = builder.add_text_field("uris", true, true);
1321        let title = builder.add_text_field("title", true, true);
1322        let schema = builder.build();
1323
1324        // Create JSON with array value
1325        let json = serde_json::json!({
1326            "uris": ["one", "two"],
1327            "title": "Test Document"
1328        });
1329
1330        // Parse from JSON
1331        let doc = Document::from_json(&json, &schema).unwrap();
1332
1333        // Verify all values are present
1334        let all_uris: Vec<_> = doc.get_all(uris).collect();
1335        assert_eq!(all_uris.len(), 2);
1336        assert_eq!(all_uris[0].as_text(), Some("one"));
1337        assert_eq!(all_uris[1].as_text(), Some("two"));
1338
1339        // Verify single value
1340        assert_eq!(
1341            doc.get_first(title).unwrap().as_text(),
1342            Some("Test Document")
1343        );
1344
1345        // Verify roundtrip: to_json should produce equivalent JSON
1346        let json_out = doc.to_json(&schema);
1347        let uris_out = json_out.get("uris").unwrap().as_array().unwrap();
1348        assert_eq!(uris_out.len(), 2);
1349        assert_eq!(uris_out[0].as_str(), Some("one"));
1350        assert_eq!(uris_out[1].as_str(), Some("two"));
1351    }
1352
1353    #[test]
1354    fn test_multi_attribute_forces_array() {
1355        // Test that fields marked as 'multi' are always serialized as arrays,
1356        // even when they have only one value
1357        let mut builder = Schema::builder();
1358        let uris = builder.add_text_field("uris", true, true);
1359        builder.set_multi(uris, true); // Mark as multi
1360        let title = builder.add_text_field("title", true, true);
1361        let schema = builder.build();
1362
1363        // Verify the multi attribute is set
1364        assert!(schema.get_field_entry(uris).unwrap().multi);
1365        assert!(!schema.get_field_entry(title).unwrap().multi);
1366
1367        // Create document with single value for multi field
1368        let mut doc = Document::new();
1369        doc.add_text(uris, "only_one");
1370        doc.add_text(title, "Test Document");
1371
1372        // Verify to_json returns array for multi field even with single value
1373        let json = doc.to_json(&schema);
1374
1375        let uris_json = json.get("uris").unwrap();
1376        assert!(
1377            uris_json.is_array(),
1378            "Multi field should be array even with single value"
1379        );
1380        let uris_arr = uris_json.as_array().unwrap();
1381        assert_eq!(uris_arr.len(), 1);
1382        assert_eq!(uris_arr[0].as_str(), Some("only_one"));
1383
1384        // Verify non-multi field with single value is NOT an array
1385        let title_json = json.get("title").unwrap();
1386        assert!(
1387            title_json.is_string(),
1388            "Non-multi single-value field should be a string"
1389        );
1390        assert_eq!(title_json.as_str(), Some("Test Document"));
1391    }
1392
1393    #[test]
1394    fn test_sparse_vector_field() {
1395        let mut builder = Schema::builder();
1396        let embedding = builder.add_sparse_vector_field("embedding", true, true);
1397        let title = builder.add_text_field("title", true, true);
1398        let schema = builder.build();
1399
1400        assert_eq!(schema.get_field("embedding"), Some(embedding));
1401        assert_eq!(
1402            schema.get_field_entry(embedding).unwrap().field_type,
1403            FieldType::SparseVector
1404        );
1405
1406        // Create document with sparse vector
1407        let mut doc = Document::new();
1408        doc.add_sparse_vector(embedding, vec![(0, 1.0), (5, 2.5), (10, 0.5)]);
1409        doc.add_text(title, "Test Document");
1410
1411        // Verify accessor
1412        let entries = doc
1413            .get_first(embedding)
1414            .unwrap()
1415            .as_sparse_vector()
1416            .unwrap();
1417        assert_eq!(entries, &[(0, 1.0), (5, 2.5), (10, 0.5)]);
1418
1419        // Verify JSON roundtrip
1420        let json = doc.to_json(&schema);
1421        let embedding_json = json.get("embedding").unwrap();
1422        assert!(embedding_json.is_object());
1423        assert_eq!(
1424            embedding_json
1425                .get("indices")
1426                .unwrap()
1427                .as_array()
1428                .unwrap()
1429                .len(),
1430            3
1431        );
1432
1433        // Parse back from JSON
1434        let doc2 = Document::from_json(&json, &schema).unwrap();
1435        let entries2 = doc2
1436            .get_first(embedding)
1437            .unwrap()
1438            .as_sparse_vector()
1439            .unwrap();
1440        assert_eq!(entries2[0].0, 0);
1441        assert!((entries2[0].1 - 1.0).abs() < 1e-6);
1442        assert_eq!(entries2[1].0, 5);
1443        assert!((entries2[1].1 - 2.5).abs() < 1e-6);
1444        assert_eq!(entries2[2].0, 10);
1445        assert!((entries2[2].1 - 0.5).abs() < 1e-6);
1446    }
1447
1448    #[test]
1449    fn test_json_field() {
1450        let mut builder = Schema::builder();
1451        let metadata = builder.add_json_field("metadata", true);
1452        let title = builder.add_text_field("title", true, true);
1453        let schema = builder.build();
1454
1455        assert_eq!(schema.get_field("metadata"), Some(metadata));
1456        assert_eq!(
1457            schema.get_field_entry(metadata).unwrap().field_type,
1458            FieldType::Json
1459        );
1460        // JSON fields are never indexed
1461        assert!(!schema.get_field_entry(metadata).unwrap().indexed);
1462        assert!(schema.get_field_entry(metadata).unwrap().stored);
1463
1464        // Create document with JSON value (object)
1465        let json_value = serde_json::json!({
1466            "author": "John Doe",
1467            "tags": ["rust", "search"],
1468            "nested": {"key": "value"}
1469        });
1470        let mut doc = Document::new();
1471        doc.add_json(metadata, json_value.clone());
1472        doc.add_text(title, "Test Document");
1473
1474        // Verify accessor
1475        let stored_json = doc.get_first(metadata).unwrap().as_json().unwrap();
1476        assert_eq!(stored_json, &json_value);
1477        assert_eq!(
1478            stored_json.get("author").unwrap().as_str(),
1479            Some("John Doe")
1480        );
1481
1482        // Verify JSON roundtrip via to_json/from_json
1483        let doc_json = doc.to_json(&schema);
1484        let metadata_out = doc_json.get("metadata").unwrap();
1485        assert_eq!(metadata_out, &json_value);
1486
1487        // Parse back from JSON
1488        let doc2 = Document::from_json(&doc_json, &schema).unwrap();
1489        let stored_json2 = doc2.get_first(metadata).unwrap().as_json().unwrap();
1490        assert_eq!(stored_json2, &json_value);
1491    }
1492
1493    #[test]
1494    fn test_json_field_various_types() {
1495        let mut builder = Schema::builder();
1496        let data = builder.add_json_field("data", true);
1497        let _schema = builder.build();
1498
1499        // Test with array
1500        let arr_value = serde_json::json!([1, 2, 3, "four", null]);
1501        let mut doc = Document::new();
1502        doc.add_json(data, arr_value.clone());
1503        assert_eq!(doc.get_first(data).unwrap().as_json().unwrap(), &arr_value);
1504
1505        // Test with string
1506        let str_value = serde_json::json!("just a string");
1507        let mut doc2 = Document::new();
1508        doc2.add_json(data, str_value.clone());
1509        assert_eq!(doc2.get_first(data).unwrap().as_json().unwrap(), &str_value);
1510
1511        // Test with number
1512        let num_value = serde_json::json!(42.5);
1513        let mut doc3 = Document::new();
1514        doc3.add_json(data, num_value.clone());
1515        assert_eq!(doc3.get_first(data).unwrap().as_json().unwrap(), &num_value);
1516
1517        // Test with null
1518        let null_value = serde_json::Value::Null;
1519        let mut doc4 = Document::new();
1520        doc4.add_json(data, null_value.clone());
1521        assert_eq!(
1522            doc4.get_first(data).unwrap().as_json().unwrap(),
1523            &null_value
1524        );
1525
1526        // Test with boolean
1527        let bool_value = serde_json::json!(true);
1528        let mut doc5 = Document::new();
1529        doc5.add_json(data, bool_value.clone());
1530        assert_eq!(
1531            doc5.get_first(data).unwrap().as_json().unwrap(),
1532            &bool_value
1533        );
1534    }
1535}