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 nprobe = self.nprobe;
177        let rerank_factor = self.rerank_factor;
178        let combiner = self.combiner;
179        Box::pin(async move {
180            let results = reader
181                .search_dense_vector(field, &vector, limit, nprobe, rerank_factor, combiner)
182                .await?;
183
184            Ok(Box::new(DenseVectorScorer::new(results, field.0)) as Box<dyn Scorer>)
185        })
186    }
187
188    fn count_estimate<'a>(&self, _reader: &'a SegmentReader) -> CountFuture<'a> {
189        Box::pin(async move { Ok(u32::MAX) })
190    }
191}
192
193/// Scorer for dense vector search results with ordinal tracking
194struct DenseVectorScorer {
195    results: Vec<VectorSearchResult>,
196    position: usize,
197    field_id: u32,
198}
199
200impl DenseVectorScorer {
201    fn new(results: Vec<VectorSearchResult>, field_id: u32) -> Self {
202        Self {
203            results,
204            position: 0,
205            field_id,
206        }
207    }
208}
209
210impl Scorer for DenseVectorScorer {
211    fn doc(&self) -> DocId {
212        if self.position < self.results.len() {
213            self.results[self.position].doc_id
214        } else {
215            TERMINATED
216        }
217    }
218
219    fn score(&self) -> Score {
220        if self.position < self.results.len() {
221            self.results[self.position].score
222        } else {
223            0.0
224        }
225    }
226
227    fn advance(&mut self) -> DocId {
228        self.position += 1;
229        self.doc()
230    }
231
232    fn seek(&mut self, target: DocId) -> DocId {
233        while self.doc() < target && self.doc() != TERMINATED {
234            self.advance();
235        }
236        self.doc()
237    }
238
239    fn size_hint(&self) -> u32 {
240        (self.results.len() - self.position) as u32
241    }
242
243    fn matched_positions(&self) -> Option<MatchedPositions> {
244        if self.position >= self.results.len() {
245            return None;
246        }
247        let result = &self.results[self.position];
248        let scored_positions: Vec<ScoredPosition> = result
249            .ordinals
250            .iter()
251            .map(|(ordinal, score)| ScoredPosition::new(*ordinal, *score))
252            .collect();
253        Some(vec![(self.field_id, scored_positions)])
254    }
255}
256
257/// Sparse vector query for similarity search
258#[derive(Debug, Clone)]
259pub struct SparseVectorQuery {
260    /// Field containing the sparse vectors
261    pub field: Field,
262    /// Query vector as (dimension_id, weight) pairs
263    pub vector: Vec<(u32, f32)>,
264    /// How to combine scores for multi-valued documents
265    pub combiner: MultiValueCombiner,
266    /// Approximate search factor (1.0 = exact, lower values = faster but approximate)
267    /// Controls WAND pruning aggressiveness in block-max scoring
268    pub heap_factor: f32,
269}
270
271impl SparseVectorQuery {
272    /// Create a new sparse vector query
273    ///
274    /// Default combiner is `LogSumExp { temperature: 0.7 }` which provides
275    /// saturation for documents with many sparse vectors (e.g., 100+ ordinals).
276    /// This prevents over-weighting from multiple matches while still allowing
277    /// additional matches to contribute to the score.
278    pub fn new(field: Field, vector: Vec<(u32, f32)>) -> Self {
279        Self {
280            field,
281            vector,
282            combiner: MultiValueCombiner::LogSumExp { temperature: 0.7 },
283            heap_factor: 1.0,
284        }
285    }
286
287    /// Set the multi-value score combiner
288    pub fn with_combiner(mut self, combiner: MultiValueCombiner) -> Self {
289        self.combiner = combiner;
290        self
291    }
292
293    /// Set the heap factor for approximate search
294    ///
295    /// Controls the trade-off between speed and recall:
296    /// - 1.0 = exact search (default)
297    /// - 0.8-0.9 = ~20-40% faster with minimal recall loss
298    /// - Lower values = more aggressive pruning, faster but lower recall
299    pub fn with_heap_factor(mut self, heap_factor: f32) -> Self {
300        self.heap_factor = heap_factor.clamp(0.0, 1.0);
301        self
302    }
303
304    /// Create from separate indices and weights vectors
305    pub fn from_indices_weights(field: Field, indices: Vec<u32>, weights: Vec<f32>) -> Self {
306        let vector: Vec<(u32, f32)> = indices.into_iter().zip(weights).collect();
307        Self::new(field, vector)
308    }
309
310    /// Create from raw text using a HuggingFace tokenizer (single segment)
311    ///
312    /// This method tokenizes the text and creates a sparse vector query.
313    /// For multi-segment indexes, use `from_text_with_stats` instead.
314    ///
315    /// # Arguments
316    /// * `field` - The sparse vector field to search
317    /// * `text` - Raw text to tokenize
318    /// * `tokenizer_name` - HuggingFace tokenizer path (e.g., "bert-base-uncased")
319    /// * `weighting` - Weighting strategy for tokens
320    /// * `sparse_index` - Optional sparse index for IDF lookup (required for IDF weighting)
321    #[cfg(feature = "native")]
322    pub fn from_text(
323        field: Field,
324        text: &str,
325        tokenizer_name: &str,
326        weighting: crate::structures::QueryWeighting,
327        sparse_index: Option<&crate::segment::SparseIndex>,
328    ) -> crate::Result<Self> {
329        use crate::structures::QueryWeighting;
330        use crate::tokenizer::tokenizer_cache;
331
332        let tokenizer = tokenizer_cache().get_or_load(tokenizer_name)?;
333        let token_ids = tokenizer.tokenize_unique(text)?;
334
335        let weights: Vec<f32> = match weighting {
336            QueryWeighting::One => vec![1.0f32; token_ids.len()],
337            QueryWeighting::Idf => {
338                if let Some(index) = sparse_index {
339                    index.idf_weights(&token_ids)
340                } else {
341                    vec![1.0f32; token_ids.len()]
342                }
343            }
344            QueryWeighting::IdfFile => {
345                use crate::tokenizer::idf_weights_cache;
346                if let Some(idf) = idf_weights_cache().get_or_load(tokenizer_name) {
347                    token_ids.iter().map(|&id| idf.get(id)).collect()
348                } else {
349                    vec![1.0f32; token_ids.len()]
350                }
351            }
352        };
353
354        let vector: Vec<(u32, f32)> = token_ids.into_iter().zip(weights).collect();
355        Ok(Self::new(field, vector))
356    }
357
358    /// Create from raw text using global statistics (multi-segment)
359    ///
360    /// This is the recommended method for multi-segment indexes as it uses
361    /// aggregated IDF values across all segments for consistent ranking.
362    ///
363    /// # Arguments
364    /// * `field` - The sparse vector field to search
365    /// * `text` - Raw text to tokenize
366    /// * `tokenizer` - Pre-loaded HuggingFace tokenizer
367    /// * `weighting` - Weighting strategy for tokens
368    /// * `global_stats` - Global statistics for IDF computation
369    #[cfg(feature = "native")]
370    pub fn from_text_with_stats(
371        field: Field,
372        text: &str,
373        tokenizer: &crate::tokenizer::HfTokenizer,
374        weighting: crate::structures::QueryWeighting,
375        global_stats: Option<&super::GlobalStats>,
376    ) -> crate::Result<Self> {
377        use crate::structures::QueryWeighting;
378
379        let token_ids = tokenizer.tokenize_unique(text)?;
380
381        let weights: Vec<f32> = match weighting {
382            QueryWeighting::One => vec![1.0f32; token_ids.len()],
383            QueryWeighting::Idf => {
384                if let Some(stats) = global_stats {
385                    // Clamp to zero: negative weights don't make sense for IDF
386                    stats
387                        .sparse_idf_weights(field, &token_ids)
388                        .into_iter()
389                        .map(|w| w.max(0.0))
390                        .collect()
391                } else {
392                    vec![1.0f32; token_ids.len()]
393                }
394            }
395            QueryWeighting::IdfFile => {
396                // IdfFile requires a tokenizer name for HF model lookup;
397                // this code path doesn't have one, so fall back to 1.0
398                vec![1.0f32; token_ids.len()]
399            }
400        };
401
402        let vector: Vec<(u32, f32)> = token_ids.into_iter().zip(weights).collect();
403        Ok(Self::new(field, vector))
404    }
405
406    /// Create from raw text, loading tokenizer from index directory
407    ///
408    /// This method supports the `index://` prefix for tokenizer paths,
409    /// loading tokenizer.json from the index directory.
410    ///
411    /// # Arguments
412    /// * `field` - The sparse vector field to search
413    /// * `text` - Raw text to tokenize
414    /// * `tokenizer_bytes` - Tokenizer JSON bytes (pre-loaded from directory)
415    /// * `weighting` - Weighting strategy for tokens
416    /// * `global_stats` - Global statistics for IDF computation
417    #[cfg(feature = "native")]
418    pub fn from_text_with_tokenizer_bytes(
419        field: Field,
420        text: &str,
421        tokenizer_bytes: &[u8],
422        weighting: crate::structures::QueryWeighting,
423        global_stats: Option<&super::GlobalStats>,
424    ) -> crate::Result<Self> {
425        use crate::structures::QueryWeighting;
426        use crate::tokenizer::HfTokenizer;
427
428        let tokenizer = HfTokenizer::from_bytes(tokenizer_bytes)?;
429        let token_ids = tokenizer.tokenize_unique(text)?;
430
431        let weights: Vec<f32> = match weighting {
432            QueryWeighting::One => vec![1.0f32; token_ids.len()],
433            QueryWeighting::Idf => {
434                if let Some(stats) = global_stats {
435                    // Clamp to zero: negative weights don't make sense for IDF
436                    stats
437                        .sparse_idf_weights(field, &token_ids)
438                        .into_iter()
439                        .map(|w| w.max(0.0))
440                        .collect()
441                } else {
442                    vec![1.0f32; token_ids.len()]
443                }
444            }
445            QueryWeighting::IdfFile => {
446                // IdfFile requires a tokenizer name for HF model lookup;
447                // this code path doesn't have one, so fall back to 1.0
448                vec![1.0f32; token_ids.len()]
449            }
450        };
451
452        let vector: Vec<(u32, f32)> = token_ids.into_iter().zip(weights).collect();
453        Ok(Self::new(field, vector))
454    }
455}
456
457impl Query for SparseVectorQuery {
458    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a> {
459        let field = self.field;
460        let vector = self.vector.clone();
461        let combiner = self.combiner;
462        let heap_factor = self.heap_factor;
463        Box::pin(async move {
464            let results = reader
465                .search_sparse_vector(field, &vector, limit, combiner, heap_factor)
466                .await?;
467
468            Ok(Box::new(SparseVectorScorer::new(results, field.0)) as Box<dyn Scorer>)
469        })
470    }
471
472    fn count_estimate<'a>(&self, _reader: &'a SegmentReader) -> CountFuture<'a> {
473        Box::pin(async move { Ok(u32::MAX) })
474    }
475}
476
477/// Scorer for sparse vector search results with ordinal tracking
478struct SparseVectorScorer {
479    results: Vec<VectorSearchResult>,
480    position: usize,
481    field_id: u32,
482}
483
484impl SparseVectorScorer {
485    fn new(results: Vec<VectorSearchResult>, field_id: u32) -> Self {
486        Self {
487            results,
488            position: 0,
489            field_id,
490        }
491    }
492}
493
494impl Scorer for SparseVectorScorer {
495    fn doc(&self) -> DocId {
496        if self.position < self.results.len() {
497            self.results[self.position].doc_id
498        } else {
499            TERMINATED
500        }
501    }
502
503    fn score(&self) -> Score {
504        if self.position < self.results.len() {
505            self.results[self.position].score
506        } else {
507            0.0
508        }
509    }
510
511    fn advance(&mut self) -> DocId {
512        self.position += 1;
513        self.doc()
514    }
515
516    fn seek(&mut self, target: DocId) -> DocId {
517        while self.doc() < target && self.doc() != TERMINATED {
518            self.advance();
519        }
520        self.doc()
521    }
522
523    fn size_hint(&self) -> u32 {
524        (self.results.len() - self.position) as u32
525    }
526
527    fn matched_positions(&self) -> Option<MatchedPositions> {
528        if self.position >= self.results.len() {
529            return None;
530        }
531        let result = &self.results[self.position];
532        let scored_positions: Vec<ScoredPosition> = result
533            .ordinals
534            .iter()
535            .map(|(ordinal, score)| ScoredPosition::new(*ordinal, *score))
536            .collect();
537        Some(vec![(self.field_id, scored_positions)])
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use crate::dsl::Field;
545
546    #[test]
547    fn test_dense_vector_query_builder() {
548        let query = DenseVectorQuery::new(Field(0), vec![1.0, 2.0, 3.0])
549            .with_nprobe(64)
550            .with_rerank_factor(5);
551
552        assert_eq!(query.field, Field(0));
553        assert_eq!(query.vector.len(), 3);
554        assert_eq!(query.nprobe, 64);
555        assert_eq!(query.rerank_factor, 5);
556    }
557
558    #[test]
559    fn test_sparse_vector_query_new() {
560        let sparse = vec![(1, 0.5), (5, 0.3), (10, 0.2)];
561        let query = SparseVectorQuery::new(Field(0), sparse.clone());
562
563        assert_eq!(query.field, Field(0));
564        assert_eq!(query.vector, sparse);
565    }
566
567    #[test]
568    fn test_sparse_vector_query_from_indices_weights() {
569        let query =
570            SparseVectorQuery::from_indices_weights(Field(0), vec![1, 5, 10], vec![0.5, 0.3, 0.2]);
571
572        assert_eq!(query.vector, vec![(1, 0.5), (5, 0.3), (10, 0.2)]);
573    }
574
575    #[test]
576    fn test_combiner_sum() {
577        let scores = vec![(0, 1.0), (1, 2.0), (2, 3.0)];
578        let combiner = MultiValueCombiner::Sum;
579        assert!((combiner.combine(&scores) - 6.0).abs() < 1e-6);
580    }
581
582    #[test]
583    fn test_combiner_max() {
584        let scores = vec![(0, 1.0), (1, 3.0), (2, 2.0)];
585        let combiner = MultiValueCombiner::Max;
586        assert!((combiner.combine(&scores) - 3.0).abs() < 1e-6);
587    }
588
589    #[test]
590    fn test_combiner_avg() {
591        let scores = vec![(0, 1.0), (1, 2.0), (2, 3.0)];
592        let combiner = MultiValueCombiner::Avg;
593        assert!((combiner.combine(&scores) - 2.0).abs() < 1e-6);
594    }
595
596    #[test]
597    fn test_combiner_log_sum_exp() {
598        let scores = vec![(0, 1.0), (1, 2.0), (2, 3.0)];
599        let combiner = MultiValueCombiner::log_sum_exp();
600        let result = combiner.combine(&scores);
601        // LogSumExp should be between max (3.0) and max + log(n)/t
602        assert!(result >= 3.0);
603        assert!(result <= 3.0 + (3.0_f32).ln() / 1.5);
604    }
605
606    #[test]
607    fn test_combiner_log_sum_exp_approaches_max_with_high_temp() {
608        let scores = vec![(0, 1.0), (1, 5.0), (2, 2.0)];
609        // High temperature should approach max
610        let combiner = MultiValueCombiner::log_sum_exp_with_temperature(10.0);
611        let result = combiner.combine(&scores);
612        // Should be very close to max (5.0)
613        assert!((result - 5.0).abs() < 0.5);
614    }
615
616    #[test]
617    fn test_combiner_weighted_top_k() {
618        let scores = vec![(0, 5.0), (1, 3.0), (2, 1.0), (3, 0.5)];
619        let combiner = MultiValueCombiner::weighted_top_k_with_params(3, 0.5);
620        let result = combiner.combine(&scores);
621        // Top 3: 5.0, 3.0, 1.0 with weights 1.0, 0.5, 0.25
622        // weighted_sum = 5*1 + 3*0.5 + 1*0.25 = 6.75
623        // weight_total = 1.75
624        // result = 6.75 / 1.75 ≈ 3.857
625        assert!((result - 3.857).abs() < 0.01);
626    }
627
628    #[test]
629    fn test_combiner_weighted_top_k_less_than_k() {
630        let scores = vec![(0, 2.0), (1, 1.0)];
631        let combiner = MultiValueCombiner::weighted_top_k_with_params(5, 0.7);
632        let result = combiner.combine(&scores);
633        // Only 2 scores, weights 1.0 and 0.7
634        // weighted_sum = 2*1 + 1*0.7 = 2.7
635        // weight_total = 1.7
636        // result = 2.7 / 1.7 ≈ 1.588
637        assert!((result - 1.588).abs() < 0.01);
638    }
639
640    #[test]
641    fn test_combiner_empty_scores() {
642        let scores: Vec<(u32, f32)> = vec![];
643        assert_eq!(MultiValueCombiner::Sum.combine(&scores), 0.0);
644        assert_eq!(MultiValueCombiner::Max.combine(&scores), 0.0);
645        assert_eq!(MultiValueCombiner::Avg.combine(&scores), 0.0);
646        assert_eq!(MultiValueCombiner::log_sum_exp().combine(&scores), 0.0);
647        assert_eq!(MultiValueCombiner::weighted_top_k().combine(&scores), 0.0);
648    }
649
650    #[test]
651    fn test_combiner_single_score() {
652        let scores = vec![(0, 5.0)];
653        // All combiners should return 5.0 for a single score
654        assert!((MultiValueCombiner::Sum.combine(&scores) - 5.0).abs() < 1e-6);
655        assert!((MultiValueCombiner::Max.combine(&scores) - 5.0).abs() < 1e-6);
656        assert!((MultiValueCombiner::Avg.combine(&scores) - 5.0).abs() < 1e-6);
657        assert!((MultiValueCombiner::log_sum_exp().combine(&scores) - 5.0).abs() < 1e-6);
658        assert!((MultiValueCombiner::weighted_top_k().combine(&scores) - 5.0).abs() < 1e-6);
659    }
660
661    #[test]
662    fn test_default_combiner_is_log_sum_exp() {
663        let combiner = MultiValueCombiner::default();
664        match combiner {
665            MultiValueCombiner::LogSumExp { temperature } => {
666                assert!((temperature - 1.5).abs() < 1e-6);
667            }
668            _ => panic!("Default combiner should be LogSumExp"),
669        }
670    }
671}