Skip to main content

hermes_core/query/
vector.rs

1//! Vector query types for dense and sparse vector search
2
3use crate::dsl::Field;
4use crate::segment::{SegmentReader, VectorSearchResult};
5use crate::{DocId, Score, TERMINATED};
6
7use super::ScoredPosition;
8use super::traits::{CountFuture, MatchedPositions, Query, Scorer, ScorerFuture};
9
10/// Strategy for combining scores when a document has multiple values for the same field
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum MultiValueCombiner {
13    /// Sum all scores (accumulates dot product contributions)
14    Sum,
15    /// Take the maximum score
16    Max,
17    /// Take the average score
18    Avg,
19    /// Log-Sum-Exp: smooth maximum approximation (default)
20    /// `score = (1/t) * log(Σ exp(t * sᵢ))`
21    /// Higher temperature → closer to max; lower → closer to mean
22    LogSumExp {
23        /// Temperature parameter (default: 1.5)
24        temperature: f32,
25    },
26    /// Weighted Top-K: weight top scores with exponential decay
27    /// `score = Σ wᵢ * sorted_scores[i]` where `wᵢ = decay^i`
28    WeightedTopK {
29        /// Number of top scores to consider (default: 5)
30        k: usize,
31        /// Decay factor per rank (default: 0.7)
32        decay: f32,
33    },
34}
35
36impl Default for MultiValueCombiner {
37    fn default() -> Self {
38        // LogSumExp with temperature 1.5 provides good balance between
39        // max (best relevance) and sum (saturation from multiple matches)
40        MultiValueCombiner::LogSumExp { temperature: 1.5 }
41    }
42}
43
44impl MultiValueCombiner {
45    /// Create LogSumExp combiner with default temperature (1.5)
46    pub fn log_sum_exp() -> Self {
47        Self::LogSumExp { temperature: 1.5 }
48    }
49
50    /// Create LogSumExp combiner with custom temperature
51    pub fn log_sum_exp_with_temperature(temperature: f32) -> Self {
52        Self::LogSumExp { temperature }
53    }
54
55    /// Create WeightedTopK combiner with defaults (k=5, decay=0.7)
56    pub fn weighted_top_k() -> Self {
57        Self::WeightedTopK { k: 5, decay: 0.7 }
58    }
59
60    /// Create WeightedTopK combiner with custom parameters
61    pub fn weighted_top_k_with_params(k: usize, decay: f32) -> Self {
62        Self::WeightedTopK { k, decay }
63    }
64
65    /// Combine multiple scores into a single score
66    pub fn combine(&self, scores: &[(u32, f32)]) -> f32 {
67        if scores.is_empty() {
68            return 0.0;
69        }
70
71        match self {
72            MultiValueCombiner::Sum => scores.iter().map(|(_, s)| s).sum(),
73            MultiValueCombiner::Max => scores
74                .iter()
75                .map(|(_, s)| *s)
76                .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
77                .unwrap_or(0.0),
78            MultiValueCombiner::Avg => {
79                let sum: f32 = scores.iter().map(|(_, s)| s).sum();
80                sum / scores.len() as f32
81            }
82            MultiValueCombiner::LogSumExp { temperature } => {
83                // Numerically stable log-sum-exp:
84                // LSE(x) = max(x) + log(Σ exp(xᵢ - max(x)))
85                let t = *temperature;
86                let max_score = scores
87                    .iter()
88                    .map(|(_, s)| *s)
89                    .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
90                    .unwrap_or(0.0);
91
92                let sum_exp: f32 = scores
93                    .iter()
94                    .map(|(_, s)| (t * (s - max_score)).exp())
95                    .sum();
96
97                max_score + sum_exp.ln() / t
98            }
99            MultiValueCombiner::WeightedTopK { k, decay } => {
100                // Sort scores descending and take top k
101                let mut sorted: Vec<f32> = scores.iter().map(|(_, s)| *s).collect();
102                sorted.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
103                sorted.truncate(*k);
104
105                // Apply exponential decay weights
106                let mut weight = 1.0f32;
107                let mut weighted_sum = 0.0f32;
108                let mut weight_total = 0.0f32;
109
110                for score in sorted {
111                    weighted_sum += weight * score;
112                    weight_total += weight;
113                    weight *= decay;
114                }
115
116                if weight_total > 0.0 {
117                    weighted_sum / weight_total
118                } else {
119                    0.0
120                }
121            }
122        }
123    }
124}
125
126/// Dense vector query for similarity search
127#[derive(Debug, Clone)]
128pub struct DenseVectorQuery {
129    /// Field containing the dense vectors
130    pub field: Field,
131    /// Query vector
132    pub vector: Vec<f32>,
133    /// Number of clusters to probe (for IVF indexes)
134    pub nprobe: usize,
135    /// Re-ranking factor (multiplied by k for candidate selection)
136    pub rerank_factor: usize,
137    /// How to combine scores for multi-valued documents
138    pub combiner: MultiValueCombiner,
139}
140
141impl DenseVectorQuery {
142    /// Create a new dense vector query
143    pub fn new(field: Field, vector: Vec<f32>) -> Self {
144        Self {
145            field,
146            vector,
147            nprobe: 32,
148            rerank_factor: 3,
149            combiner: MultiValueCombiner::Max,
150        }
151    }
152
153    /// Set the number of clusters to probe (for IVF indexes)
154    pub fn with_nprobe(mut self, nprobe: usize) -> Self {
155        self.nprobe = nprobe;
156        self
157    }
158
159    /// Set the re-ranking factor
160    pub fn with_rerank_factor(mut self, factor: usize) -> Self {
161        self.rerank_factor = factor;
162        self
163    }
164
165    /// Set the multi-value score combiner
166    pub fn with_combiner(mut self, combiner: MultiValueCombiner) -> Self {
167        self.combiner = combiner;
168        self
169    }
170}
171
172impl Query for DenseVectorQuery {
173    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a> {
174        let field = self.field;
175        let vector = self.vector.clone();
176        let rerank_factor = self.rerank_factor;
177        let combiner = self.combiner;
178        Box::pin(async move {
179            let results =
180                reader.search_dense_vector(field, &vector, limit, rerank_factor, combiner)?;
181
182            Ok(Box::new(DenseVectorScorer::new(results, field.0)) as Box<dyn Scorer>)
183        })
184    }
185
186    fn count_estimate<'a>(&self, _reader: &'a SegmentReader) -> CountFuture<'a> {
187        Box::pin(async move { Ok(u32::MAX) })
188    }
189}
190
191/// Scorer for dense vector search results with ordinal tracking
192struct DenseVectorScorer {
193    results: Vec<VectorSearchResult>,
194    position: usize,
195    field_id: u32,
196}
197
198impl DenseVectorScorer {
199    fn new(results: Vec<VectorSearchResult>, field_id: u32) -> Self {
200        Self {
201            results,
202            position: 0,
203            field_id,
204        }
205    }
206}
207
208impl Scorer for DenseVectorScorer {
209    fn doc(&self) -> DocId {
210        if self.position < self.results.len() {
211            self.results[self.position].doc_id
212        } else {
213            TERMINATED
214        }
215    }
216
217    fn score(&self) -> Score {
218        if self.position < self.results.len() {
219            self.results[self.position].score
220        } else {
221            0.0
222        }
223    }
224
225    fn advance(&mut self) -> DocId {
226        self.position += 1;
227        self.doc()
228    }
229
230    fn seek(&mut self, target: DocId) -> DocId {
231        while self.doc() < target && self.doc() != TERMINATED {
232            self.advance();
233        }
234        self.doc()
235    }
236
237    fn size_hint(&self) -> u32 {
238        (self.results.len() - self.position) as u32
239    }
240
241    fn matched_positions(&self) -> Option<MatchedPositions> {
242        if self.position >= self.results.len() {
243            return None;
244        }
245        let result = &self.results[self.position];
246        let scored_positions: Vec<ScoredPosition> = result
247            .ordinals
248            .iter()
249            .map(|(ordinal, score)| ScoredPosition::new(*ordinal, *score))
250            .collect();
251        Some(vec![(self.field_id, scored_positions)])
252    }
253}
254
255/// Sparse vector query for similarity search
256#[derive(Debug, Clone)]
257pub struct SparseVectorQuery {
258    /// Field containing the sparse vectors
259    pub field: Field,
260    /// Query vector as (dimension_id, weight) pairs
261    pub vector: Vec<(u32, f32)>,
262    /// How to combine scores for multi-valued documents
263    pub combiner: MultiValueCombiner,
264    /// Approximate search factor (1.0 = exact, lower values = faster but approximate)
265    /// Controls WAND pruning aggressiveness in block-max scoring
266    pub heap_factor: f32,
267}
268
269impl SparseVectorQuery {
270    /// Create a new sparse vector query
271    pub fn new(field: Field, vector: Vec<(u32, f32)>) -> Self {
272        Self {
273            field,
274            vector,
275            combiner: MultiValueCombiner::Sum,
276            heap_factor: 1.0,
277        }
278    }
279
280    /// Set the multi-value score combiner
281    pub fn with_combiner(mut self, combiner: MultiValueCombiner) -> Self {
282        self.combiner = combiner;
283        self
284    }
285
286    /// Set the heap factor for approximate search
287    ///
288    /// Controls the trade-off between speed and recall:
289    /// - 1.0 = exact search (default)
290    /// - 0.8-0.9 = ~20-40% faster with minimal recall loss
291    /// - Lower values = more aggressive pruning, faster but lower recall
292    pub fn with_heap_factor(mut self, heap_factor: f32) -> Self {
293        self.heap_factor = heap_factor.clamp(0.0, 1.0);
294        self
295    }
296
297    /// Create from separate indices and weights vectors
298    pub fn from_indices_weights(field: Field, indices: Vec<u32>, weights: Vec<f32>) -> Self {
299        let vector: Vec<(u32, f32)> = indices.into_iter().zip(weights).collect();
300        Self::new(field, vector)
301    }
302
303    /// Create from raw text using a HuggingFace tokenizer (single segment)
304    ///
305    /// This method tokenizes the text and creates a sparse vector query.
306    /// For multi-segment indexes, use `from_text_with_stats` instead.
307    ///
308    /// # Arguments
309    /// * `field` - The sparse vector field to search
310    /// * `text` - Raw text to tokenize
311    /// * `tokenizer_name` - HuggingFace tokenizer path (e.g., "bert-base-uncased")
312    /// * `weighting` - Weighting strategy for tokens
313    /// * `sparse_index` - Optional sparse index for IDF lookup (required for IDF weighting)
314    #[cfg(feature = "native")]
315    pub fn from_text(
316        field: Field,
317        text: &str,
318        tokenizer_name: &str,
319        weighting: crate::structures::QueryWeighting,
320        sparse_index: Option<&crate::segment::SparseIndex>,
321    ) -> crate::Result<Self> {
322        use crate::structures::QueryWeighting;
323        use crate::tokenizer::tokenizer_cache;
324
325        let tokenizer = tokenizer_cache().get_or_load(tokenizer_name)?;
326        let token_ids = tokenizer.tokenize_unique(text)?;
327
328        let weights: Vec<f32> = match weighting {
329            QueryWeighting::One => vec![1.0f32; token_ids.len()],
330            QueryWeighting::Idf => {
331                if let Some(index) = sparse_index {
332                    index.idf_weights(&token_ids)
333                } else {
334                    vec![1.0f32; token_ids.len()]
335                }
336            }
337            QueryWeighting::IdfFile => {
338                use crate::tokenizer::idf_weights_cache;
339                if let Some(idf) = idf_weights_cache().get_or_load(tokenizer_name) {
340                    token_ids.iter().map(|&id| idf.get(id)).collect()
341                } else {
342                    vec![1.0f32; token_ids.len()]
343                }
344            }
345        };
346
347        let vector: Vec<(u32, f32)> = token_ids.into_iter().zip(weights).collect();
348        Ok(Self::new(field, vector))
349    }
350
351    /// Create from raw text using global statistics (multi-segment)
352    ///
353    /// This is the recommended method for multi-segment indexes as it uses
354    /// aggregated IDF values across all segments for consistent ranking.
355    ///
356    /// # Arguments
357    /// * `field` - The sparse vector field to search
358    /// * `text` - Raw text to tokenize
359    /// * `tokenizer` - Pre-loaded HuggingFace tokenizer
360    /// * `weighting` - Weighting strategy for tokens
361    /// * `global_stats` - Global statistics for IDF computation
362    #[cfg(feature = "native")]
363    pub fn from_text_with_stats(
364        field: Field,
365        text: &str,
366        tokenizer: &crate::tokenizer::HfTokenizer,
367        weighting: crate::structures::QueryWeighting,
368        global_stats: Option<&super::GlobalStats>,
369    ) -> crate::Result<Self> {
370        use crate::structures::QueryWeighting;
371
372        let token_ids = tokenizer.tokenize_unique(text)?;
373
374        let weights: Vec<f32> = match weighting {
375            QueryWeighting::One => vec![1.0f32; token_ids.len()],
376            QueryWeighting::Idf => {
377                if let Some(stats) = global_stats {
378                    // Clamp to zero: negative weights don't make sense for IDF
379                    stats
380                        .sparse_idf_weights(field, &token_ids)
381                        .into_iter()
382                        .map(|w| w.max(0.0))
383                        .collect()
384                } else {
385                    vec![1.0f32; token_ids.len()]
386                }
387            }
388            QueryWeighting::IdfFile => {
389                // IdfFile requires a tokenizer name for HF model lookup;
390                // this code path doesn't have one, so fall back to 1.0
391                vec![1.0f32; token_ids.len()]
392            }
393        };
394
395        let vector: Vec<(u32, f32)> = token_ids.into_iter().zip(weights).collect();
396        Ok(Self::new(field, vector))
397    }
398
399    /// Create from raw text, loading tokenizer from index directory
400    ///
401    /// This method supports the `index://` prefix for tokenizer paths,
402    /// loading tokenizer.json from the index directory.
403    ///
404    /// # Arguments
405    /// * `field` - The sparse vector field to search
406    /// * `text` - Raw text to tokenize
407    /// * `tokenizer_bytes` - Tokenizer JSON bytes (pre-loaded from directory)
408    /// * `weighting` - Weighting strategy for tokens
409    /// * `global_stats` - Global statistics for IDF computation
410    #[cfg(feature = "native")]
411    pub fn from_text_with_tokenizer_bytes(
412        field: Field,
413        text: &str,
414        tokenizer_bytes: &[u8],
415        weighting: crate::structures::QueryWeighting,
416        global_stats: Option<&super::GlobalStats>,
417    ) -> crate::Result<Self> {
418        use crate::structures::QueryWeighting;
419        use crate::tokenizer::HfTokenizer;
420
421        let tokenizer = HfTokenizer::from_bytes(tokenizer_bytes)?;
422        let token_ids = tokenizer.tokenize_unique(text)?;
423
424        let weights: Vec<f32> = match weighting {
425            QueryWeighting::One => vec![1.0f32; token_ids.len()],
426            QueryWeighting::Idf => {
427                if let Some(stats) = global_stats {
428                    // Clamp to zero: negative weights don't make sense for IDF
429                    stats
430                        .sparse_idf_weights(field, &token_ids)
431                        .into_iter()
432                        .map(|w| w.max(0.0))
433                        .collect()
434                } else {
435                    vec![1.0f32; token_ids.len()]
436                }
437            }
438            QueryWeighting::IdfFile => {
439                // IdfFile requires a tokenizer name for HF model lookup;
440                // this code path doesn't have one, so fall back to 1.0
441                vec![1.0f32; token_ids.len()]
442            }
443        };
444
445        let vector: Vec<(u32, f32)> = token_ids.into_iter().zip(weights).collect();
446        Ok(Self::new(field, vector))
447    }
448}
449
450impl Query for SparseVectorQuery {
451    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a> {
452        let field = self.field;
453        let vector = self.vector.clone();
454        let combiner = self.combiner;
455        let heap_factor = self.heap_factor;
456        Box::pin(async move {
457            let results = reader
458                .search_sparse_vector(field, &vector, limit, combiner, heap_factor)
459                .await?;
460
461            Ok(Box::new(SparseVectorScorer::new(results, field.0)) as Box<dyn Scorer>)
462        })
463    }
464
465    fn count_estimate<'a>(&self, _reader: &'a SegmentReader) -> CountFuture<'a> {
466        Box::pin(async move { Ok(u32::MAX) })
467    }
468}
469
470/// Scorer for sparse vector search results with ordinal tracking
471struct SparseVectorScorer {
472    results: Vec<VectorSearchResult>,
473    position: usize,
474    field_id: u32,
475}
476
477impl SparseVectorScorer {
478    fn new(results: Vec<VectorSearchResult>, field_id: u32) -> Self {
479        Self {
480            results,
481            position: 0,
482            field_id,
483        }
484    }
485}
486
487impl Scorer for SparseVectorScorer {
488    fn doc(&self) -> DocId {
489        if self.position < self.results.len() {
490            self.results[self.position].doc_id
491        } else {
492            TERMINATED
493        }
494    }
495
496    fn score(&self) -> Score {
497        if self.position < self.results.len() {
498            self.results[self.position].score
499        } else {
500            0.0
501        }
502    }
503
504    fn advance(&mut self) -> DocId {
505        self.position += 1;
506        self.doc()
507    }
508
509    fn seek(&mut self, target: DocId) -> DocId {
510        while self.doc() < target && self.doc() != TERMINATED {
511            self.advance();
512        }
513        self.doc()
514    }
515
516    fn size_hint(&self) -> u32 {
517        (self.results.len() - self.position) as u32
518    }
519
520    fn matched_positions(&self) -> Option<MatchedPositions> {
521        if self.position >= self.results.len() {
522            return None;
523        }
524        let result = &self.results[self.position];
525        let scored_positions: Vec<ScoredPosition> = result
526            .ordinals
527            .iter()
528            .map(|(ordinal, score)| ScoredPosition::new(*ordinal, *score))
529            .collect();
530        Some(vec![(self.field_id, scored_positions)])
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537    use crate::dsl::Field;
538
539    #[test]
540    fn test_dense_vector_query_builder() {
541        let query = DenseVectorQuery::new(Field(0), vec![1.0, 2.0, 3.0])
542            .with_nprobe(64)
543            .with_rerank_factor(5);
544
545        assert_eq!(query.field, Field(0));
546        assert_eq!(query.vector.len(), 3);
547        assert_eq!(query.nprobe, 64);
548        assert_eq!(query.rerank_factor, 5);
549    }
550
551    #[test]
552    fn test_sparse_vector_query_new() {
553        let sparse = vec![(1, 0.5), (5, 0.3), (10, 0.2)];
554        let query = SparseVectorQuery::new(Field(0), sparse.clone());
555
556        assert_eq!(query.field, Field(0));
557        assert_eq!(query.vector, sparse);
558    }
559
560    #[test]
561    fn test_sparse_vector_query_from_indices_weights() {
562        let query =
563            SparseVectorQuery::from_indices_weights(Field(0), vec![1, 5, 10], vec![0.5, 0.3, 0.2]);
564
565        assert_eq!(query.vector, vec![(1, 0.5), (5, 0.3), (10, 0.2)]);
566    }
567
568    #[test]
569    fn test_combiner_sum() {
570        let scores = vec![(0, 1.0), (1, 2.0), (2, 3.0)];
571        let combiner = MultiValueCombiner::Sum;
572        assert!((combiner.combine(&scores) - 6.0).abs() < 1e-6);
573    }
574
575    #[test]
576    fn test_combiner_max() {
577        let scores = vec![(0, 1.0), (1, 3.0), (2, 2.0)];
578        let combiner = MultiValueCombiner::Max;
579        assert!((combiner.combine(&scores) - 3.0).abs() < 1e-6);
580    }
581
582    #[test]
583    fn test_combiner_avg() {
584        let scores = vec![(0, 1.0), (1, 2.0), (2, 3.0)];
585        let combiner = MultiValueCombiner::Avg;
586        assert!((combiner.combine(&scores) - 2.0).abs() < 1e-6);
587    }
588
589    #[test]
590    fn test_combiner_log_sum_exp() {
591        let scores = vec![(0, 1.0), (1, 2.0), (2, 3.0)];
592        let combiner = MultiValueCombiner::log_sum_exp();
593        let result = combiner.combine(&scores);
594        // LogSumExp should be between max (3.0) and max + log(n)/t
595        assert!(result >= 3.0);
596        assert!(result <= 3.0 + (3.0_f32).ln() / 1.5);
597    }
598
599    #[test]
600    fn test_combiner_log_sum_exp_approaches_max_with_high_temp() {
601        let scores = vec![(0, 1.0), (1, 5.0), (2, 2.0)];
602        // High temperature should approach max
603        let combiner = MultiValueCombiner::log_sum_exp_with_temperature(10.0);
604        let result = combiner.combine(&scores);
605        // Should be very close to max (5.0)
606        assert!((result - 5.0).abs() < 0.5);
607    }
608
609    #[test]
610    fn test_combiner_weighted_top_k() {
611        let scores = vec![(0, 5.0), (1, 3.0), (2, 1.0), (3, 0.5)];
612        let combiner = MultiValueCombiner::weighted_top_k_with_params(3, 0.5);
613        let result = combiner.combine(&scores);
614        // Top 3: 5.0, 3.0, 1.0 with weights 1.0, 0.5, 0.25
615        // weighted_sum = 5*1 + 3*0.5 + 1*0.25 = 6.75
616        // weight_total = 1.75
617        // result = 6.75 / 1.75 ≈ 3.857
618        assert!((result - 3.857).abs() < 0.01);
619    }
620
621    #[test]
622    fn test_combiner_weighted_top_k_less_than_k() {
623        let scores = vec![(0, 2.0), (1, 1.0)];
624        let combiner = MultiValueCombiner::weighted_top_k_with_params(5, 0.7);
625        let result = combiner.combine(&scores);
626        // Only 2 scores, weights 1.0 and 0.7
627        // weighted_sum = 2*1 + 1*0.7 = 2.7
628        // weight_total = 1.7
629        // result = 2.7 / 1.7 ≈ 1.588
630        assert!((result - 1.588).abs() < 0.01);
631    }
632
633    #[test]
634    fn test_combiner_empty_scores() {
635        let scores: Vec<(u32, f32)> = vec![];
636        assert_eq!(MultiValueCombiner::Sum.combine(&scores), 0.0);
637        assert_eq!(MultiValueCombiner::Max.combine(&scores), 0.0);
638        assert_eq!(MultiValueCombiner::Avg.combine(&scores), 0.0);
639        assert_eq!(MultiValueCombiner::log_sum_exp().combine(&scores), 0.0);
640        assert_eq!(MultiValueCombiner::weighted_top_k().combine(&scores), 0.0);
641    }
642
643    #[test]
644    fn test_combiner_single_score() {
645        let scores = vec![(0, 5.0)];
646        // All combiners should return 5.0 for a single score
647        assert!((MultiValueCombiner::Sum.combine(&scores) - 5.0).abs() < 1e-6);
648        assert!((MultiValueCombiner::Max.combine(&scores) - 5.0).abs() < 1e-6);
649        assert!((MultiValueCombiner::Avg.combine(&scores) - 5.0).abs() < 1e-6);
650        assert!((MultiValueCombiner::log_sum_exp().combine(&scores) - 5.0).abs() < 1e-6);
651        assert!((MultiValueCombiner::weighted_top_k().combine(&scores) - 5.0).abs() < 1e-6);
652    }
653
654    #[test]
655    fn test_default_combiner_is_log_sum_exp() {
656        let combiner = MultiValueCombiner::default();
657        match combiner {
658            MultiValueCombiner::LogSumExp { temperature } => {
659                assert!((temperature - 1.5).abs() < 1e-6);
660            }
661            _ => panic!("Default combiner should be LogSumExp"),
662        }
663    }
664}