Skip to main content

otters/
meta.rs

1//! Vector search with metadata pruning (MetaStore)
2//!
3//! Chunks vectors, builds per-column zonemaps (min/max/nulls and small Bloom
4//! filters), and uses them to prune work before running SIMD scoring. Supports
5//! combining metadata expressions with vector filters and top‑k selection.
6use std::collections::HashMap;
7use std::time::{Duration, Instant};
8
9use crate::{
10    col::{self, Column},
11    expr::{CmpOp, ColumnFilter, CompiledFilter, Expr, NumericLiteral},
12    meta_compute::{
13        BloomBuild, ChunkAgg, MetaChunk, ZoneStat, build_zone_stat_for_range, process_chunk,
14    },
15    type_utils::DataType,
16    vec::{Cmp as VecCmp, Metric, TakeType, VecStore},
17};
18use bitvec::bitvec;
19use bitvec::prelude::BitVec;
20use itertools::Itertools;
21use rayon::prelude::*;
22
23pub struct MetaQueryResults {
24    pub columns: Vec<String>,
25    pub data: HashMap<String, Column>,
26    pub indices: Vec<usize>,
27    pub scores: Vec<f32>,
28}
29
30impl MetaQueryResults {
31    pub fn len(&self) -> usize {
32        self.indices.len()
33    }
34    pub fn is_empty(&self) -> bool {
35        self.indices.is_empty()
36    }
37    pub fn column(&self, name: &str) -> Option<&Column> {
38        self.data.get(name)
39    }
40}
41
42#[derive(Debug, Clone, Copy)]
43pub enum BloomConfig {
44    Fpr(f64),
45    Bits(usize),
46}
47
48#[derive(Debug)]
49pub struct MetaStore {
50    schema: HashMap<String, DataType>,
51    columns: HashMap<String, Column>,
52    chunk_size: usize,
53    chunks: Vec<MetaChunk>,
54    last_stats: std::cell::RefCell<Option<MetaQueryStats>>,
55    build_stats: Option<MetaBuildStats>,
56    packed_ranges_f64: HashMap<String, PackedRanges<f64>>,
57    packed_ranges_i64: HashMap<String, PackedRanges<i64>>,
58    packed_ranges_f32: HashMap<String, PackedRanges<f32>>,
59    packed_ranges_i32: HashMap<String, PackedRanges<i32>>,
60}
61
62#[derive(Debug)]
63pub struct MetaStoreBuilder {
64    schema: HashMap<String, DataType>,
65    columns: HashMap<String, Column>,
66    vectors: Option<Vec<Vec<f32>>>,
67    chunk_size: usize,
68    bloom: BloomConfig,
69}
70
71#[derive(Debug, Default, Clone)]
72struct PackedRanges<T> {
73    min: Vec<T>,
74    max: Vec<T>,
75    non_null: Vec<usize>,
76}
77
78impl MetaStoreBuilder {
79    /// Supply vectors to build the store (row-major f32 per vector).
80    pub fn with_vectors(mut self, vectors: Vec<Vec<f32>>) -> Self {
81        self.vectors = Some(vectors);
82        self
83    }
84
85    /// Set the chunk size used for pruning granularity.
86    pub fn with_chunk_size(mut self, chunk_size: usize) -> Self {
87        self.chunk_size = chunk_size.max(1);
88        self
89    }
90
91    /// Configure Bloom filters by false-positive rate.
92    pub fn with_bloom_fpr(mut self, fpr: f64) -> Self {
93        // Clamp to sane bounds, fallback to default when non-finite
94        let f = if fpr.is_finite() {
95            fpr.clamp(1e-2, 0.5)
96        } else {
97            0.01
98        };
99        self.bloom = BloomConfig::Fpr(f);
100        self
101    }
102
103    /// Configure bloom filter by total number of bits.
104    /// Use this to size the filter explicitly (e.g. 1024, 4096, ...).
105    /// Configure Bloom filters by explicit size in bits.
106    pub fn with_bloom_bits(mut self, bits: usize) -> Self {
107        let b = bits.max(64); // minimal sane floor
108        self.bloom = BloomConfig::Bits(b);
109        self
110    }
111
112    // Supply a single fully-built column for a name from the schema
113    pub fn with_column(mut self, name: &str, column: Column) -> Result<Self, String> {
114        let expected = *self
115            .schema
116            .get(name)
117            .ok_or_else(|| format!("unknown column '{name}' not present in schema"))?;
118        if expected != column.dtype() {
119            return Err(format!(
120                "dtype mismatch for column '{}': schema {:?}, got {:?}",
121                name,
122                expected,
123                column.dtype()
124            ));
125        }
126        self.columns.insert(name.to_string(), column);
127        Ok(self)
128    }
129
130    // Supply multiple fully-built columns and validates against schema
131    pub fn with_columns(mut self, columns: Vec<(String, Column)>) -> Result<Self, String> {
132        for (name, col) in columns {
133            let expected = *self
134                .schema
135                .get(&name)
136                .ok_or_else(|| format!("unknown column '{name}' not present in schema"))?;
137            if expected != col.dtype() {
138                return Err(format!(
139                    "dtype mismatch for column '{}': schema {:?}, got {:?}",
140                    name,
141                    expected,
142                    col.dtype()
143                ));
144            }
145            self.columns.insert(name, col);
146        }
147        Ok(self)
148    }
149
150    /// Finalize the builder and construct a `MetaStore`.
151    pub fn build(self) -> Result<MetaStore, String> {
152        // Validate vectors/columns lengths
153        let vectors = self
154            .vectors
155            .ok_or_else(|| "vectors must be provided to build MetaStore".to_string())?;
156
157        let n_rows = vectors.len();
158
159        // every column in schema must be present and have the same length as vectors
160        for name in self.schema.keys() {
161            let col = self
162                .columns
163                .get(name)
164                .ok_or_else(|| format!("missing column '{name}' in builder columns"))?;
165            if col.len() != n_rows {
166                return Err(format!(
167                    "column '{}' length {} does not match vectors length {}",
168                    name,
169                    col.len(),
170                    n_rows
171                ));
172            }
173        }
174
175        // Derive vector dimension
176        let dim = if n_rows > 0 { vectors[0].len() } else { 0 };
177        if dim == 0 && n_rows > 0 {
178            return Err("vector dimension cannot be zero".to_string());
179        }
180        for (i, v) in vectors.iter().enumerate() {
181            if v.len() != dim {
182                return Err(format!(
183                    "vector at index {} has dim {}, expected {}",
184                    i,
185                    v.len(),
186                    dim
187                ));
188            }
189        }
190
191        // Timings
192        let build_start = Instant::now();
193        let mut vectors_ingest_duration = Duration::default();
194        let mut zonemap_build_duration = Duration::default();
195
196        let mut packed_ranges_f64: HashMap<String, PackedRanges<f64>> = HashMap::new();
197        let mut packed_ranges_i64: HashMap<String, PackedRanges<i64>> = HashMap::new();
198        let mut packed_ranges_f32: HashMap<String, PackedRanges<f32>> = HashMap::new();
199        let mut packed_ranges_i32: HashMap<String, PackedRanges<i32>> = HashMap::new();
200
201        let mut chunks: Vec<MetaChunk> = Vec::new();
202        let mut base_offset = 0usize;
203        for chunk_iter in &vectors.into_iter().chunks(self.chunk_size) {
204            let chunk_vecs: Vec<Vec<f32>> = chunk_iter.collect();
205            if chunk_vecs.is_empty() {
206                continue;
207            }
208
209            let mut vs = VecStore::new(dim);
210            let ingest_start = Instant::now();
211            vs.add_vectors(chunk_vecs)?;
212            vectors_ingest_duration += ingest_start.elapsed();
213
214            let end = base_offset + vs.len();
215
216            // Build stats for this chunk
217            let zstart = Instant::now();
218            let bloom_cfg = match self.bloom {
219                BloomConfig::Fpr(p) => BloomBuild::Fpr(p),
220                BloomConfig::Bits(b) => BloomBuild::Bits(b),
221            };
222            let stats: HashMap<String, ZoneStat> = self
223                .schema
224                .iter()
225                .map(|(name, dtype)| {
226                    let col = self
227                        .columns
228                        .get(name)
229                        .ok_or_else(|| format!("missing column '{name}' in builder columns"))?;
230                    let stat = build_zone_stat_for_range(col, *dtype, base_offset, end, bloom_cfg)?;
231                    Ok::<(String, ZoneStat), String>((name.clone(), stat))
232                })
233                .collect::<Result<_, _>>()?;
234            zonemap_build_duration += zstart.elapsed();
235
236            // Append packed per-chunk ranges
237            self.schema
238                .iter()
239                .for_each(|(name, dtype)| match (dtype, stats.get(name).unwrap()) {
240                    (DataType::Float32, ZoneStat::Float { min, max, non_null }) => {
241                        let e32 = packed_ranges_f32.entry(name.clone()).or_default();
242                        e32.min.push(*min as f32);
243                        e32.max.push(*max as f32);
244                        e32.non_null.push(*non_null);
245                    }
246                    (DataType::Float64, ZoneStat::Float { min, max, non_null }) => {
247                        let entry = packed_ranges_f64.entry(name.clone()).or_default();
248                        entry.min.push(*min);
249                        entry.max.push(*max);
250                        entry.non_null.push(*non_null);
251                    }
252                    (DataType::Int32, ZoneStat::Int { min, max, non_null }) => {
253                        let e32 = packed_ranges_i32.entry(name.clone()).or_default();
254                        e32.min.push(*min as i32);
255                        e32.max.push(*max as i32);
256                        e32.non_null.push(*non_null);
257                    }
258                    (DataType::Int64, ZoneStat::Int { min, max, non_null }) => {
259                        let entry = packed_ranges_i64.entry(name.clone()).or_default();
260                        entry.min.push(*min);
261                        entry.max.push(*max);
262                        entry.non_null.push(*non_null);
263                    }
264                    (DataType::DateTime, ZoneStat::DateTime { min, max, non_null }) => {
265                        let entry = packed_ranges_i64.entry(name.clone()).or_default();
266                        entry.min.push(*min);
267                        entry.max.push(*max);
268                        entry.non_null.push(*non_null);
269                    }
270                    _ => {}
271                });
272
273            chunks.push(MetaChunk {
274                base_offset,
275                len: end - base_offset,
276                vec_store: vs,
277                stats,
278            });
279
280            base_offset = end;
281        }
282
283        let build_total_duration = build_start.elapsed();
284        let n_chunks = chunks.len();
285
286        Ok(MetaStore {
287            schema: self.schema,
288            columns: self.columns,
289            chunk_size: self.chunk_size,
290            chunks,
291            last_stats: std::cell::RefCell::new(None),
292            build_stats: Some(MetaBuildStats {
293                n_rows,
294                dim,
295                n_chunks,
296                vectors_ingest_duration,
297                zonemap_build_duration,
298                build_total_duration,
299            }),
300            packed_ranges_f64,
301            packed_ranges_i64,
302            packed_ranges_f32,
303            packed_ranges_i32,
304        })
305    }
306}
307
308impl MetaStore {
309    /// Create an empty MetaStore from a `(name, DataType)` schema.
310    pub fn new(schema: &[(String, DataType)]) -> Self {
311        let schema_map = HashMap::from_iter(schema.iter().cloned());
312        let columns = HashMap::from_iter(
313            schema
314                .iter()
315                .map(|(name, dtype)| (name.clone(), col::Column::new(name, *dtype))),
316        );
317        Self {
318            schema: schema_map,
319            columns,
320            chunk_size: 1024,
321            chunks: Vec::new(),
322            last_stats: std::cell::RefCell::new(None),
323            build_stats: None,
324            packed_ranges_f64: HashMap::new(),
325            packed_ranges_i64: HashMap::new(),
326            packed_ranges_f32: HashMap::new(),
327            packed_ranges_i32: HashMap::new(),
328        }
329    }
330
331    /// Start a builder from fully-constructed columns.
332    pub fn from_columns(columns: Vec<Column>) -> MetaStoreBuilder {
333        let mut schema = HashMap::new();
334        let mut col_map = HashMap::new();
335        for col in columns {
336            let name = col.name().to_string();
337            schema.insert(name.clone(), col.dtype());
338            col_map.insert(name, col);
339        }
340        MetaStoreBuilder {
341            schema,
342            columns: col_map,
343            vectors: None,
344            chunk_size: 1024,
345            bloom: BloomConfig::Fpr(0.01),
346        }
347    }
348
349    /// Start a builder from a schema; columns default to empty.
350    pub fn from_schema(schema: &[(String, DataType)]) -> MetaStoreBuilder {
351        let mut schema_map = HashMap::new();
352        let mut columns = HashMap::new();
353        for (name, dt) in schema {
354            schema_map.insert(name.clone(), *dt);
355            columns.insert(name.clone(), Column::new(name, *dt));
356        }
357        MetaStoreBuilder {
358            schema: schema_map,
359            columns,
360            vectors: None,
361            chunk_size: 1024,
362            bloom: BloomConfig::Fpr(0.01),
363        }
364    }
365
366    /// Print a small head preview (first 5 rows) as an ASCII table.
367    pub fn head(&self) {
368        self.head_n(5)
369    }
370
371    /// Print the first `n` rows as an ASCII table.
372    pub fn head_n(&self, n: usize) {
373        println!("{}", crate::display::metastore_head(self, n));
374    }
375
376    // Accessors for display helpers
377    /// Access the schema map.
378    pub fn schema(&self) -> &HashMap<String, DataType> {
379        &self.schema
380    }
381    /// Access the backing columns.
382    pub fn columns(&self) -> &HashMap<String, Column> {
383        &self.columns
384    }
385    /// Number of chunks in the store.
386    pub fn n_chunks(&self) -> usize {
387        self.chunks.len()
388    }
389    /// Configured chunk size.
390    pub fn chunk_size(&self) -> usize {
391        self.chunk_size
392    }
393
394    /// Stats from the most recent query, if any.
395    pub fn last_query_stats(&self) -> Option<MetaQueryStats> {
396        self.last_stats.borrow().clone()
397    }
398
399    /// Return build-time stats captured when the MetaStore was constructed.
400    /// Build-time stats captured during construction.
401    pub fn build_stats(&self) -> Option<MetaBuildStats> {
402        self.build_stats.clone()
403    }
404
405    // Build a per-chunk mask for the compiled plan
406    // the pruning logic used during query planning. True indicates the chunk may satisfy the plan.
407    fn build_chunk_mask_for_plan(&self, compiled: &CompiledFilter) -> BitVec {
408        let n_chunks = self.chunks.len();
409        if n_chunks == 0 {
410            return BitVec::new();
411        }
412        compiled
413            .clauses
414            .iter()
415            .fold(bitvec![1; n_chunks], |mut acc, clause| {
416                let mut clause_mask = bitvec![0; n_chunks];
417                clause.iter().for_each(|leaf| match leaf {
418                    ColumnFilter::Numeric { column, cmp, rhs } => {
419                        self.apply_numeric_leaf_chunk_mask(&mut clause_mask, column, *cmp, rhs);
420                    }
421                    ColumnFilter::String { column, cmp, rhs } => {
422                        self.apply_string_leaf_chunk_mask(&mut clause_mask, column, *cmp, rhs);
423                    }
424                });
425                acc &= &clause_mask;
426                acc
427            })
428    }
429
430    // Leaf helpers for chunk preselection
431    fn apply_numeric_leaf_chunk_mask(
432        &self,
433        mask: &mut BitVec,
434        column: &str,
435        cmp: CmpOp,
436        rhs: &NumericLiteral,
437    ) {
438        let n_chunks = mask.len();
439        match rhs {
440            NumericLiteral::F64(rv) => match self.schema.get(column) {
441                Some(DataType::Float32) => {
442                    if let Some(packed) = self.packed_ranges_f32.get(column) {
443                        crate::type_utils::apply_chunk_mask_ranges_f32_bits(
444                            &packed.min,
445                            &packed.max,
446                            &packed.non_null,
447                            n_chunks,
448                            cmp,
449                            *rv as f32,
450                            mask,
451                        );
452                    }
453                }
454                Some(DataType::Float64) => {
455                    if let Some(packed) = self.packed_ranges_f64.get(column) {
456                        crate::type_utils::apply_chunk_mask_ranges_f64_bits(
457                            &packed.min,
458                            &packed.max,
459                            &packed.non_null,
460                            n_chunks,
461                            cmp,
462                            *rv,
463                            mask,
464                        );
465                    }
466                }
467                _ => {
468                    if let Some(packed) = self.packed_ranges_i64.get(column) {
469                        crate::type_utils::apply_chunk_mask_ranges_i64_bits(
470                            &packed.min,
471                            &packed.max,
472                            &packed.non_null,
473                            n_chunks,
474                            cmp,
475                            *rv as i64,
476                            mask,
477                        );
478                    }
479                }
480            },
481            NumericLiteral::I64(rv) => match self.schema.get(column) {
482                Some(DataType::Int32) => {
483                    if let Some(packed) = self.packed_ranges_i32.get(column) {
484                        crate::type_utils::apply_chunk_mask_ranges_i32_bits(
485                            &packed.min,
486                            &packed.max,
487                            &packed.non_null,
488                            n_chunks,
489                            cmp,
490                            *rv as i32,
491                            mask,
492                        );
493                    }
494                }
495                Some(DataType::Int64) | Some(DataType::DateTime) => {
496                    if let Some(packed) = self.packed_ranges_i64.get(column) {
497                        crate::type_utils::apply_chunk_mask_ranges_i64_bits(
498                            &packed.min,
499                            &packed.max,
500                            &packed.non_null,
501                            n_chunks,
502                            cmp,
503                            *rv,
504                            mask,
505                        );
506                    } else if let Some(packed) = self.packed_ranges_f64.get(column) {
507                        crate::type_utils::apply_chunk_mask_ranges_f64_bits(
508                            &packed.min,
509                            &packed.max,
510                            &packed.non_null,
511                            n_chunks,
512                            cmp,
513                            *rv as f64,
514                            mask,
515                        );
516                    }
517                }
518                _ => {}
519            },
520        }
521    }
522
523    fn apply_string_leaf_chunk_mask(&self, mask: &mut BitVec, column: &str, cmp: CmpOp, rhs: &str) {
524        for (i, chunk) in self.chunks.iter().enumerate() {
525            if let Some(ZoneStat::String { bloom, non_null }) = chunk.stats.get(column) {
526                if *non_null == 0 {
527                    continue;
528                }
529                match cmp {
530                    CmpOp::Eq => {
531                        if bloom.contains(rhs.as_bytes()) {
532                            mask.set(i, true);
533                        }
534                    }
535                    CmpOp::Neq => {
536                        mask.set(i, true);
537                    }
538                    _ => {}
539                }
540            } else {
541                mask.set(i, true); // conservatively keep when unknown
542            }
543        }
544    }
545
546    /// Print build-time stats as a table.
547    pub fn print_build_stats(&self) {
548        match &self.build_stats {
549            Some(b) => println!("{}", crate::display::format_build_stats(b)),
550            None => println!("(no build stats)"),
551        }
552    }
553
554    /// Print the last query stats as a table.
555    pub fn print_last_query_stats(&self) {
556        match self.last_query_stats() {
557            Some(s) => println!("{}", crate::display::format_query_stats(&s)),
558            None => println!("(no query stats)"),
559        }
560    }
561
562    /// Print build and last query stats.
563    pub fn print_last_stats(&self) {
564        self.print_build_stats();
565        self.print_last_query_stats();
566    }
567
568    /// Start a query with a single vector and metric.
569    pub fn query(&self, query: Vec<f32>, metric: Metric) -> MetaQueryPlan<'_> {
570        MetaQueryPlan::new(self, vec![query], metric)
571    }
572
573    /// Start a query with multiple vectors.
574    pub fn query_batch(&self, queries: Vec<Vec<f32>>, metric: Metric) -> MetaQueryPlan<'_> {
575        MetaQueryPlan::new(self, queries, metric)
576    }
577}
578
579#[derive(Debug)]
580pub struct MetaQueryPlan<'a> {
581    store: &'a MetaStore,
582    queries: Vec<Vec<f32>>,
583    metric: Metric,
584    meta_filter: Option<CompiledFilter>,
585    meta_error: Option<String>,
586    vec_filter: Option<(f32, VecCmp)>,
587    take_type: Option<TakeType>,
588    take_count: Option<usize>,
589}
590
591impl<'a> MetaQueryPlan<'a> {
592    fn new(store: &'a MetaStore, queries: Vec<Vec<f32>>, metric: Metric) -> Self {
593        Self {
594            store,
595            queries,
596            metric,
597            meta_filter: None,
598            meta_error: None,
599            vec_filter: None,
600            take_type: None,
601            take_count: None,
602        }
603    }
604
605    pub fn meta_filter(mut self, expr: Expr) -> Self {
606        match expr.compile(&self.store.schema) {
607            Ok(compiled) => {
608                self.meta_filter = Some(compiled);
609                self.meta_error = None;
610            }
611            Err(e) => {
612                self.meta_error = Some(format!("meta_filter compile error: {e}"));
613            }
614        }
615        self
616    }
617
618    pub fn vec_filter(mut self, score: f32, cmp: VecCmp) -> Self {
619        self.vec_filter = Some((score, cmp));
620        self
621    }
622
623    pub fn take(mut self, k: usize) -> Self {
624        self.take_count = Some(k);
625        self.take_type = Some(match self.metric {
626            Metric::Euclidean => TakeType::Min,
627            Metric::Cosine | Metric::DotProduct => TakeType::Max,
628        });
629        self
630    }
631
632    pub fn collect(self) -> Result<MetaQueryResults, String> {
633        // Surface any deferred meta filter compilation errors first
634        if let Some(err) = self.meta_error {
635            return Err(err);
636        }
637        let total_start = Instant::now();
638        let k = self
639            .take_count
640            .unwrap_or_else(|| self.store.chunks.iter().map(|c| c.len).sum());
641        let take_type = self.take_type.unwrap_or(match self.metric {
642            Metric::Euclidean => TakeType::Min,
643            _ => TakeType::Max,
644        });
645
646        // Preselect chunks via zone stats
647        let prune_start = Instant::now();
648        let candidate_chunks: Vec<&MetaChunk> = match self.meta_filter.as_ref() {
649            Some(compiled) => self
650                .store
651                .build_chunk_mask_for_plan(compiled)
652                .iter()
653                .by_vals()
654                .enumerate()
655                .filter(|&(_, keep)| keep)
656                .map(|(i, _)| &self.store.chunks[i])
657                .collect(),
658            None => self.store.chunks.iter().collect(),
659        };
660        let prune_duration = prune_start.elapsed();
661
662        // Aggregated results into a single list across all queries
663        let mut aggregated: Vec<(usize, f32)> = Vec::new();
664
665        // Stats counters
666        let total_chunks = self.store.chunks.len();
667        let evaluated_chunks = candidate_chunks.len();
668        let pruned_chunks = total_chunks - evaluated_chunks;
669        let mut vectors_compared: usize = 0;
670
671        let score_start = Instant::now();
672        let metric_ref = &self.metric;
673        let queries_ref = &self.queries;
674        let vec_filter_opt = self.vec_filter.clone();
675        let meta_filter_ref = self.meta_filter.as_ref();
676        let columns_ref = &self.store.columns;
677
678        let per_chunk: Vec<ChunkAgg> = candidate_chunks
679            .par_iter()
680            .map(|c| {
681                process_chunk(
682                    c,
683                    metric_ref,
684                    queries_ref,
685                    vec_filter_opt.clone(),
686                    meta_filter_ref,
687                    columns_ref,
688                    k,
689                )
690            })
691            .collect();
692
693        per_chunk.into_iter().for_each(|agg| {
694            vectors_compared += agg.compared;
695            aggregated.extend(agg.results);
696        });
697        let score_duration = score_start.elapsed();
698
699        let merge_start = Instant::now();
700        // Final top-k per bucket
701        // sort and truncate final list
702        match take_type {
703            TakeType::Min => aggregated.sort_unstable_by(|a, b| a.1.partial_cmp(&b.1).unwrap()),
704            TakeType::Max => aggregated.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap()),
705        }
706        if aggregated.len() > k {
707            aggregated.truncate(k);
708        }
709        let merge_duration = merge_start.elapsed();
710        let total_duration = total_start.elapsed();
711        let stats = MetaQueryStats {
712            total_chunks,
713            pruned_chunks,
714            evaluated_chunks,
715            vectors_compared,
716            prune_duration,
717            score_duration,
718            merge_duration,
719            total_duration,
720        };
721        *self.store.last_stats.borrow_mut() = Some(stats);
722        // Build result columns and collect indices/scores in result order
723        let mut col_names: Vec<String> = self.store.schema.keys().cloned().collect();
724        col_names.sort();
725
726        let (indices, scores): (Vec<usize>, Vec<f32>) = aggregated.iter().cloned().unzip();
727
728        // Materialize typed columns with values copied from source columns
729        let mut data: HashMap<String, Column> = HashMap::with_capacity(col_names.len());
730        for name in &col_names {
731            if let Some(src) = self.store.columns.get(name) {
732                let mut dst = Column::new(name, src.dtype());
733                match src.dtype() {
734                    DataType::Int32 => {
735                        let vals = src.i32_values().unwrap();
736                        let nulls = src.null_mask();
737                        indices
738                            .iter()
739                            .try_for_each(|&gi| {
740                                if nulls.get(gi).map(|b| *b).unwrap_or(false) {
741                                    dst.push(Option::<i32>::None)
742                                } else {
743                                    dst.push(vals[gi])
744                                }
745                            })
746                            .map_err(|e| e.to_string())?;
747                    }
748                    DataType::Int64 => {
749                        let vals = src.i64_values().unwrap();
750                        let nulls = src.null_mask();
751                        indices
752                            .iter()
753                            .try_for_each(|&gi| {
754                                if nulls.get(gi).map(|b| *b).unwrap_or(false) {
755                                    dst.push(Option::<i64>::None)
756                                } else {
757                                    dst.push(vals[gi])
758                                }
759                            })
760                            .map_err(|e| e.to_string())?;
761                    }
762                    DataType::Float32 => {
763                        let vals = src.f32_values().unwrap();
764                        let nulls = src.null_mask();
765                        indices
766                            .iter()
767                            .try_for_each(|&gi| {
768                                if nulls.get(gi).map(|b| *b).unwrap_or(false) {
769                                    dst.push(Option::<f32>::None)
770                                } else {
771                                    dst.push(vals[gi])
772                                }
773                            })
774                            .map_err(|e| e.to_string())?;
775                    }
776                    DataType::Float64 => {
777                        let vals = src.f64_values().unwrap();
778                        let nulls = src.null_mask();
779                        indices
780                            .iter()
781                            .try_for_each(|&gi| {
782                                if nulls.get(gi).map(|b| *b).unwrap_or(false) {
783                                    dst.push(Option::<f64>::None)
784                                } else {
785                                    dst.push(vals[gi])
786                                }
787                            })
788                            .map_err(|e| e.to_string())?;
789                    }
790                    DataType::String => {
791                        let vals = src.string_values().unwrap();
792                        let nulls = src.null_mask();
793                        indices
794                            .iter()
795                            .try_for_each(|&gi| {
796                                if nulls.get(gi).map(|b| *b).unwrap_or(false) {
797                                    dst.push(Option::<&str>::None)
798                                } else {
799                                    dst.push(vals[gi].as_str())
800                                }
801                            })
802                            .map_err(|e| e.to_string())?;
803                    }
804                    DataType::DateTime => {
805                        let vals = src.datetime_values().unwrap();
806                        let nulls = src.null_mask();
807                        indices
808                            .iter()
809                            .try_for_each(|&gi| {
810                                if nulls.get(gi).map(|b| *b).unwrap_or(false) {
811                                    dst.push(crate::col::ColumnValue::DateTime(None))
812                                } else {
813                                    dst.push(crate::col::ColumnValue::DateTime(Some(vals[gi])))
814                                }
815                            })
816                            .map_err(|e| e.to_string())?;
817                    }
818                }
819                data.insert(name.clone(), dst);
820            }
821        }
822
823        Ok(MetaQueryResults {
824            columns: col_names,
825            data,
826            indices,
827            scores,
828        })
829    }
830}
831
832#[derive(Debug, Clone)]
833pub struct MetaQueryStats {
834    pub total_chunks: usize,
835    pub pruned_chunks: usize,
836    pub evaluated_chunks: usize,
837    pub vectors_compared: usize,
838    pub prune_duration: Duration,
839    pub score_duration: Duration,
840    pub merge_duration: Duration,
841    pub total_duration: Duration,
842}
843
844#[derive(Debug, Clone)]
845pub struct MetaBuildStats {
846    pub n_rows: usize,
847    pub dim: usize,
848    pub n_chunks: usize,
849    pub vectors_ingest_duration: Duration,
850    pub zonemap_build_duration: Duration,
851    pub build_total_duration: Duration,
852}