lance_index/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4//! Lance secondary index library
5//!
6//! <section class="warning">
7//! This is internal crate used by <a href="https://github.com/lancedb/lance">the lance project</a>.
8//! <br/>
9//! API stability is not guaranteed.
10//! </section>
11
12use std::{any::Any, sync::Arc};
13
14use crate::frag_reuse::FRAG_REUSE_INDEX_NAME;
15use crate::mem_wal::MEM_WAL_INDEX_NAME;
16use async_trait::async_trait;
17use deepsize::DeepSizeOf;
18use lance_core::{Error, Result};
19use roaring::RoaringBitmap;
20use serde::{Deserialize, Serialize};
21use snafu::location;
22use std::convert::TryFrom;
23
24pub mod frag_reuse;
25pub mod mem_wal;
26pub mod metrics;
27pub mod optimize;
28pub mod prefilter;
29pub mod scalar;
30pub mod traits;
31pub mod vector;
32
33pub use crate::traits::*;
34
35pub const INDEX_FILE_NAME: &str = "index.idx";
36/// The name of the auxiliary index file.
37///
38/// This file is used to store additional information about the index, to improve performance.
39/// - For 'IVF_HNSW' index, it stores the partitioned PQ Storage.
40pub const INDEX_AUXILIARY_FILE_NAME: &str = "auxiliary.idx";
41pub const INDEX_METADATA_SCHEMA_KEY: &str = "lance:index";
42
43// Currently all vector indexes are version 1
44pub const VECTOR_INDEX_VERSION: u32 = 1;
45
46pub mod pb {
47    #![allow(clippy::use_self)]
48    include!(concat!(env!("OUT_DIR"), "/lance.index.pb.rs"));
49}
50
51pub mod pbold {
52    #![allow(clippy::use_self)]
53    include!(concat!(env!("OUT_DIR"), "/lance.table.rs"));
54}
55
56/// Generic methods common across all types of secondary indices
57///
58#[async_trait]
59pub trait Index: Send + Sync + DeepSizeOf {
60    /// Cast to [Any].
61    fn as_any(&self) -> &dyn Any;
62
63    /// Cast to [Index]
64    fn as_index(self: Arc<Self>) -> Arc<dyn Index>;
65
66    /// Cast to [vector::VectorIndex]
67    fn as_vector_index(self: Arc<Self>) -> Result<Arc<dyn vector::VectorIndex>>;
68
69    /// Retrieve index statistics as a JSON Value
70    fn statistics(&self) -> Result<serde_json::Value>;
71
72    /// Prewarm the index.
73    ///
74    /// This will load the index into memory and cache it.
75    async fn prewarm(&self) -> Result<()>;
76
77    /// Get the type of the index
78    fn index_type(&self) -> IndexType;
79
80    /// Read through the index and determine which fragment ids are covered by the index
81    ///
82    /// This is a kind of slow operation.  It's better to use the fragment_bitmap.  This
83    /// only exists for cases where the fragment_bitmap has become corrupted or missing.
84    async fn calculate_included_frags(&self) -> Result<RoaringBitmap>;
85}
86
87/// Index Type
88#[derive(Debug, PartialEq, Eq, Copy, Hash, Clone, DeepSizeOf)]
89pub enum IndexType {
90    // Preserve 0-100 for simple indices.
91    Scalar = 0, // Legacy scalar index, alias to BTree
92
93    BTree = 1, // BTree
94
95    Bitmap = 2, // Bitmap
96
97    LabelList = 3, // LabelList
98
99    Inverted = 4, // Inverted
100
101    NGram = 5, // NGram
102
103    FragmentReuse = 6,
104
105    MemWal = 7,
106
107    ZoneMap = 8, // ZoneMap
108
109    BloomFilter = 9, // Bloom filter
110
111    // 100+ and up for vector index.
112    /// Flat vector index.
113    Vector = 100, // Legacy vector index, alias to IvfPq
114    IvfFlat = 101,
115    IvfSq = 102,
116    IvfPq = 103,
117    IvfHnswSq = 104,
118    IvfHnswPq = 105,
119    IvfHnswFlat = 106,
120}
121
122impl std::fmt::Display for IndexType {
123    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
124        match self {
125            Self::Scalar | Self::BTree => write!(f, "BTree"),
126            Self::Bitmap => write!(f, "Bitmap"),
127            Self::LabelList => write!(f, "LabelList"),
128            Self::Inverted => write!(f, "Inverted"),
129            Self::NGram => write!(f, "NGram"),
130            Self::FragmentReuse => write!(f, "FragmentReuse"),
131            Self::MemWal => write!(f, "MemWal"),
132            Self::ZoneMap => write!(f, "ZoneMap"),
133            Self::BloomFilter => write!(f, "BloomFilter"),
134            Self::Vector | Self::IvfPq => write!(f, "IVF_PQ"),
135            Self::IvfFlat => write!(f, "IVF_FLAT"),
136            Self::IvfSq => write!(f, "IVF_SQ"),
137            Self::IvfHnswSq => write!(f, "IVF_HNSW_SQ"),
138            Self::IvfHnswPq => write!(f, "IVF_HNSW_PQ"),
139            Self::IvfHnswFlat => write!(f, "IVF_HNSW_FLAT"),
140        }
141    }
142}
143
144impl TryFrom<i32> for IndexType {
145    type Error = Error;
146
147    fn try_from(value: i32) -> Result<Self> {
148        match value {
149            v if v == Self::Scalar as i32 => Ok(Self::Scalar),
150            v if v == Self::BTree as i32 => Ok(Self::BTree),
151            v if v == Self::Bitmap as i32 => Ok(Self::Bitmap),
152            v if v == Self::LabelList as i32 => Ok(Self::LabelList),
153            v if v == Self::NGram as i32 => Ok(Self::NGram),
154            v if v == Self::Inverted as i32 => Ok(Self::Inverted),
155            v if v == Self::FragmentReuse as i32 => Ok(Self::FragmentReuse),
156            v if v == Self::MemWal as i32 => Ok(Self::MemWal),
157            v if v == Self::ZoneMap as i32 => Ok(Self::ZoneMap),
158            v if v == Self::BloomFilter as i32 => Ok(Self::BloomFilter),
159            v if v == Self::Vector as i32 => Ok(Self::Vector),
160            v if v == Self::IvfFlat as i32 => Ok(Self::IvfFlat),
161            v if v == Self::IvfSq as i32 => Ok(Self::IvfSq),
162            v if v == Self::IvfPq as i32 => Ok(Self::IvfPq),
163            v if v == Self::IvfHnswSq as i32 => Ok(Self::IvfHnswSq),
164            v if v == Self::IvfHnswPq as i32 => Ok(Self::IvfHnswPq),
165            v if v == Self::IvfHnswFlat as i32 => Ok(Self::IvfHnswFlat),
166            _ => Err(Error::InvalidInput {
167                source: format!("the input value {} is not a valid IndexType", value).into(),
168                location: location!(),
169            }),
170        }
171    }
172}
173
174impl TryFrom<&str> for IndexType {
175    type Error = Error;
176
177    fn try_from(value: &str) -> Result<Self> {
178        match value {
179            "BTree" => Ok(Self::BTree),
180            "Bitmap" => Ok(Self::Bitmap),
181            "LabelList" => Ok(Self::LabelList),
182            "Inverted" => Ok(Self::Inverted),
183            "NGram" => Ok(Self::NGram),
184            "FragmentReuse" => Ok(Self::FragmentReuse),
185            "MemWal" => Ok(Self::MemWal),
186            "ZoneMap" => Ok(Self::ZoneMap),
187            "Vector" => Ok(Self::Vector),
188            "IVF_FLAT" => Ok(Self::IvfFlat),
189            "IVF_SQ" => Ok(Self::IvfSq),
190            "IVF_PQ" => Ok(Self::IvfPq),
191            "IVF_HNSW_FLAT" => Ok(Self::IvfHnswFlat),
192            "IVF_HNSW_SQ" => Ok(Self::IvfHnswSq),
193            "IVF_HNSW_PQ" => Ok(Self::IvfHnswPq),
194            _ => Err(Error::invalid_input(
195                format!("invalid index type: {}", value),
196                location!(),
197            )),
198        }
199    }
200}
201
202impl IndexType {
203    pub fn is_scalar(&self) -> bool {
204        matches!(
205            self,
206            Self::Scalar
207                | Self::BTree
208                | Self::Bitmap
209                | Self::LabelList
210                | Self::Inverted
211                | Self::NGram
212                | Self::ZoneMap
213                | Self::BloomFilter
214        )
215    }
216
217    pub fn is_vector(&self) -> bool {
218        matches!(
219            self,
220            Self::Vector
221                | Self::IvfPq
222                | Self::IvfHnswSq
223                | Self::IvfHnswPq
224                | Self::IvfHnswFlat
225                | Self::IvfFlat
226                | Self::IvfSq
227        )
228    }
229
230    pub fn is_system(&self) -> bool {
231        matches!(self, Self::FragmentReuse | Self::MemWal)
232    }
233
234    /// Returns the current format version of the index type,
235    /// bump this when the index format changes.
236    /// Indices which higher version than these will be ignored for compatibility,
237    /// This would happen when creating index in a newer version of Lance,
238    /// but then opening the index in older version of Lance
239    pub fn version(&self) -> i32 {
240        match self {
241            Self::Scalar => 0,
242            Self::BTree => 0,
243            Self::Bitmap => 0,
244            Self::LabelList => 0,
245            Self::Inverted => 0,
246            Self::NGram => 0,
247            Self::FragmentReuse => 0,
248            Self::MemWal => 0,
249            Self::ZoneMap => 0,
250            Self::BloomFilter => 0,
251
252            // for now all vector indices are built by the same builder,
253            // so they share the same version.
254            Self::Vector
255            | Self::IvfFlat
256            | Self::IvfSq
257            | Self::IvfPq
258            | Self::IvfHnswSq
259            | Self::IvfHnswPq
260            | Self::IvfHnswFlat => 1,
261        }
262    }
263
264    /// Returns the target partition size for the index type.
265    ///
266    /// This is used to compute the number of partitions for the index.
267    /// The partition size is optimized for the best performance of the index.
268    ///
269    /// This is for vector indices only.
270    pub fn target_partition_size(&self) -> usize {
271        match self {
272            Self::Vector => 8192,
273            Self::IvfFlat => 4096,
274            Self::IvfSq => 8192,
275            Self::IvfPq => 8192,
276            Self::IvfHnswFlat => 1 << 20,
277            Self::IvfHnswSq => 1 << 20,
278            Self::IvfHnswPq => 1 << 20,
279            _ => 8192,
280        }
281    }
282}
283
284pub trait IndexParams: Send + Sync {
285    fn as_any(&self) -> &dyn Any;
286
287    fn index_name(&self) -> &str;
288}
289
290#[derive(Serialize, Deserialize, Debug)]
291pub struct IndexMetadata {
292    #[serde(rename = "type")]
293    pub index_type: String,
294    pub distance_type: String,
295}
296
297pub fn is_system_index(index_meta: &lance_table::format::IndexMetadata) -> bool {
298    index_meta.name == FRAG_REUSE_INDEX_NAME || index_meta.name == MEM_WAL_INDEX_NAME
299}
300
301pub fn infer_system_index_type(
302    index_meta: &lance_table::format::IndexMetadata,
303) -> Option<IndexType> {
304    if index_meta.name == FRAG_REUSE_INDEX_NAME {
305        Some(IndexType::FragmentReuse)
306    } else if index_meta.name == MEM_WAL_INDEX_NAME {
307        Some(IndexType::MemWal)
308    } else {
309        None
310    }
311}