store_api/storage/
requests.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::{Display, Formatter};
16
17use common_error::ext::BoxedError;
18use common_recordbatch::OrderOption;
19use datafusion_expr::expr::Expr;
20// Re-export vector types from datatypes to avoid duplication
21pub use datatypes::schema::{VectorDistanceMetric, VectorIndexEngineType};
22use strum::Display;
23
24use crate::storage::{ColumnId, SequenceNumber};
25
26/// A hint for KNN vector search.
27#[derive(Debug, Clone, PartialEq)]
28pub struct VectorSearchRequest {
29    /// Column ID of the vector column to search.
30    pub column_id: ColumnId,
31    /// The query vector to search for.
32    pub query_vector: Vec<f32>,
33    /// Number of nearest neighbors to return.
34    pub k: usize,
35    /// Distance metric to use (matches the index metric).
36    pub metric: VectorDistanceMetric,
37}
38
39/// Search results from vector index.
40#[derive(Debug, Clone, PartialEq)]
41pub struct VectorSearchMatches {
42    /// Keys (row offsets in the index).
43    pub keys: Vec<u64>,
44    /// Distances from the query vector.
45    pub distances: Vec<f32>,
46}
47
48/// Trait for vector index engines (HNSW implementations).
49///
50/// This trait defines the interface for pluggable vector index engines.
51/// Implementations (e.g., UsearchEngine) are provided by storage engines like mito2.
52pub trait VectorIndexEngine: Send + Sync {
53    /// Adds a vector with the given key.
54    fn add(&mut self, key: u64, vector: &[f32]) -> Result<(), BoxedError>;
55
56    /// Searches for k nearest neighbors.
57    fn search(&self, query: &[f32], k: usize) -> Result<VectorSearchMatches, BoxedError>;
58
59    /// Returns the serialized length.
60    fn serialized_length(&self) -> usize;
61
62    /// Serializes the index to a buffer.
63    fn save_to_buffer(&self, buffer: &mut [u8]) -> Result<(), BoxedError>;
64
65    /// Reserves capacity for vectors.
66    fn reserve(&mut self, capacity: usize) -> Result<(), BoxedError>;
67
68    /// Returns current size (number of vectors).
69    fn size(&self) -> usize;
70
71    /// Returns current capacity.
72    fn capacity(&self) -> usize;
73
74    /// Returns memory usage in bytes.
75    fn memory_usage(&self) -> usize;
76}
77
78/// A hint on how to select rows from a time-series.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display)]
80pub enum TimeSeriesRowSelector {
81    /// Only keep the last row of each time-series.
82    LastRow,
83}
84
85/// A hint on how to distribute time-series data on the scan output.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display)]
87pub enum TimeSeriesDistribution {
88    /// Data are distributed by time window first. The scanner will
89    /// return all data within one time window before moving to the next one.
90    TimeWindowed,
91    /// Data are organized by time-series first. The scanner will return
92    /// all data for one time-series before moving to the next one.
93    PerSeries,
94}
95
96#[derive(Default, Clone, Debug, PartialEq)]
97pub struct ScanRequest {
98    /// Indices of columns to read, `None` to read all columns. This indices is
99    /// based on table schema.
100    pub projection: Option<Vec<usize>>,
101    /// Filters pushed down
102    pub filters: Vec<Expr>,
103    /// Expected output ordering. This is only a hint and isn't guaranteed.
104    pub output_ordering: Option<Vec<OrderOption>>,
105    /// limit can be used to reduce the amount scanned
106    /// from the datasource as a performance optimization.
107    /// If set, it contains the amount of rows needed by the caller,
108    /// The data source should return *at least* this number of rows if available.
109    pub limit: Option<usize>,
110    /// Optional hint to select rows from time-series.
111    pub series_row_selector: Option<TimeSeriesRowSelector>,
112    /// Optional constraint on the sequence number of the rows to read.
113    /// If set, only rows with a sequence number **lesser or equal** to this value
114    /// will be returned.
115    pub memtable_max_sequence: Option<SequenceNumber>,
116    /// Optional constraint on the minimal sequence number in the memtable.
117    /// If set, only the memtables that contain sequences **greater than** this value will be scanned
118    pub memtable_min_sequence: Option<SequenceNumber>,
119    /// Optional constraint on the minimal sequence number in the SST files.
120    /// If set, only the SST files that contain sequences greater than this value will be scanned.
121    pub sst_min_sequence: Option<SequenceNumber>,
122    /// Optional hint for the distribution of time-series data.
123    pub distribution: Option<TimeSeriesDistribution>,
124    /// Optional hint for KNN vector search. When set, the scan should use
125    /// vector index to find the k nearest neighbors.
126    pub vector_search: Option<VectorSearchRequest>,
127    /// Whether to force reading region data in flat format.
128    pub force_flat_format: bool,
129}
130
131impl Display for ScanRequest {
132    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
133        enum Delimiter {
134            None,
135            Init,
136        }
137
138        impl Delimiter {
139            fn as_str(&mut self) -> &str {
140                match self {
141                    Delimiter::None => {
142                        *self = Delimiter::Init;
143                        ""
144                    }
145                    Delimiter::Init => ", ",
146                }
147            }
148        }
149
150        let mut delimiter = Delimiter::None;
151
152        write!(f, "ScanRequest {{ ")?;
153        if let Some(projection) = &self.projection {
154            write!(f, "{}projection: {:?}", delimiter.as_str(), projection)?;
155        }
156        if !self.filters.is_empty() {
157            write!(
158                f,
159                "{}filters: [{}]",
160                delimiter.as_str(),
161                self.filters
162                    .iter()
163                    .map(|f| f.to_string())
164                    .collect::<Vec<_>>()
165                    .join(", ")
166            )?;
167        }
168        if let Some(output_ordering) = &self.output_ordering {
169            write!(
170                f,
171                "{}output_ordering: {:?}",
172                delimiter.as_str(),
173                output_ordering
174            )?;
175        }
176        if let Some(limit) = &self.limit {
177            write!(f, "{}limit: {}", delimiter.as_str(), limit)?;
178        }
179        if let Some(series_row_selector) = &self.series_row_selector {
180            write!(
181                f,
182                "{}series_row_selector: {}",
183                delimiter.as_str(),
184                series_row_selector
185            )?;
186        }
187        if let Some(sequence) = &self.memtable_max_sequence {
188            write!(f, "{}sequence: {}", delimiter.as_str(), sequence)?;
189        }
190        if let Some(sst_min_sequence) = &self.sst_min_sequence {
191            write!(
192                f,
193                "{}sst_min_sequence: {}",
194                delimiter.as_str(),
195                sst_min_sequence
196            )?;
197        }
198        if let Some(distribution) = &self.distribution {
199            write!(f, "{}distribution: {}", delimiter.as_str(), distribution)?;
200        }
201        if let Some(vector_search) = &self.vector_search {
202            write!(
203                f,
204                "{}vector_search: column_id={}, k={}, metric={}",
205                delimiter.as_str(),
206                vector_search.column_id,
207                vector_search.k,
208                vector_search.metric
209            )?;
210        }
211        if self.force_flat_format {
212            write!(
213                f,
214                "{}force_flat_format: {}",
215                delimiter.as_str(),
216                self.force_flat_format
217            )?;
218        }
219        write!(f, " }}")
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use datafusion_expr::{Operator, binary_expr, col, lit};
226
227    use super::*;
228
229    #[test]
230    fn test_display_scan_request() {
231        let request = ScanRequest {
232            ..Default::default()
233        };
234        assert_eq!(request.to_string(), "ScanRequest {  }");
235
236        let request = ScanRequest {
237            projection: Some(vec![1, 2]),
238            filters: vec![
239                binary_expr(col("i"), Operator::Gt, lit(1)),
240                binary_expr(col("s"), Operator::Eq, lit("x")),
241            ],
242            limit: Some(10),
243            ..Default::default()
244        };
245        assert_eq!(
246            request.to_string(),
247            r#"ScanRequest { projection: [1, 2], filters: [i > Int32(1), s = Utf8("x")], limit: 10 }"#
248        );
249
250        let request = ScanRequest {
251            filters: vec![
252                binary_expr(col("i"), Operator::Gt, lit(1)),
253                binary_expr(col("s"), Operator::Eq, lit("x")),
254            ],
255            limit: Some(10),
256            ..Default::default()
257        };
258        assert_eq!(
259            request.to_string(),
260            r#"ScanRequest { filters: [i > Int32(1), s = Utf8("x")], limit: 10 }"#
261        );
262
263        let request = ScanRequest {
264            projection: Some(vec![1, 2]),
265            limit: Some(10),
266            ..Default::default()
267        };
268        assert_eq!(
269            request.to_string(),
270            "ScanRequest { projection: [1, 2], limit: 10 }"
271        );
272
273        let request = ScanRequest {
274            force_flat_format: true,
275            ..Default::default()
276        };
277        assert_eq!(
278            request.to_string(),
279            "ScanRequest { force_flat_format: true }"
280        );
281    }
282}