Elffuss BraidHub

kikocis/lancedb public

fix: `list_indices` returns correct index type (#1715)

Fixes https://github.com/lancedb/lancedb/issues/1711

Doesn't address this https://github.com/lancedb/lance/issues/2039

Instead we load the index statistics, which seems to contain the index
type. However, this involves more IO than previously. I'm not sure
whether we care that much. If we do, we can fix that upstream Lance
issue.
Changeset70d43ccc8e377886000a80205a91f8dd1c7acdd8a03ed15c149ac55b548aade4
AuthorWill Jones <willjones127@gmail.com> · 2024-10-01 09:16 -07:00
CommitterGitHub <noreply@github.com> · 2024-10-01 09:16 -07:00
Parentscdf1aa093b13

Browse the files at this changeset

3 files changed

modified python/python/tests/test_index.py +4 −6
@@ -63,9 +63,8 @@
6363 @pytest.mark.asyncio
6464 async def test_create_bitmap_index(some_table: AsyncTable):
6565 await some_table.create_index("id", config=Bitmap())
66- # TODO: Fix via https://github.com/lancedb/lance/issues/2039
67- # indices = await some_table.list_indices()
68- # assert str(indices) == '[Index(Bitmap, columns=["id"])]'
66+ indices = await some_table.list_indices()
67+ assert str(indices) == '[Index(Bitmap, columns=["id"])]'
6968 indices = await some_table.list_indices()
7069 assert len(indices) == 1
7170 index_name = indices[0].name
@@ -80,9 +79,8 @@
8079 @pytest.mark.asyncio
8180 async def test_create_label_list_index(some_table: AsyncTable):
8281 await some_table.create_index("tags", config=LabelList())
83- # TODO: Fix via https://github.com/lancedb/lance/issues/2039
84- # indices = await some_table.list_indices()
85- # assert str(indices) == '[Index(LabelList, columns=["id"])]'
82+ indices = await some_table.list_indices()
83+ assert str(indices) == '[Index(LabelList, columns=["tags"])]'
8684
8785
8886 @pytest.mark.asyncio
modified rust/lancedb/src/index.rs +20 −1
@@ -18,7 +18,7 @@
1818 use serde::Deserialize;
1919 use serde_with::skip_serializing_none;
2020
21-use crate::{table::TableInternal, DistanceType, Result};
21+use crate::{table::TableInternal, DistanceType, Error, Result};
2222
2323 use self::{
2424 scalar::{BTreeIndexBuilder, BitmapIndexBuilder, LabelListIndexBuilder},
@@ -136,6 +136,25 @@
136136 }
137137 }
138138
139+impl std::str::FromStr for IndexType {
140+ type Err = Error;
141+
142+ fn from_str(value: &str) -> Result<Self> {
143+ match value.to_uppercase().as_str() {
144+ "BTREE" => Ok(Self::BTree),
145+ "BITMAP" => Ok(Self::Bitmap),
146+ "LABEL_LIST" | "LABELLIST" => Ok(Self::LabelList),
147+ "FTS" => Ok(Self::FTS),
148+ "IVF_PQ" => Ok(Self::IvfPq),
149+ "IVF_HNSW_PQ" => Ok(Self::IvfHnswPq),
150+ "IVF_HNSW_SQ" => Ok(Self::IvfHnswSq),
151+ _ => Err(Error::InvalidInput {
152+ message: format!("the input value {} is not a valid IndexType", value),
153+ }),
154+ }
155+ }
156+}
157+
139158 /// A description of an index currently configured on a column
140159 #[derive(Debug, PartialEq, Clone)]
141160 pub struct IndexConfig {
modified rust/lancedb/src/table.rs +17 −16
@@ -25,6 +25,7 @@
2525 use async_trait::async_trait;
2626 use datafusion_physical_plan::display::DisplayableExecutionPlan;
2727 use datafusion_physical_plan::ExecutionPlan;
28+use futures::{StreamExt, TryStreamExt};
2829 use lance::dataset::builder::DatasetBuilder;
2930 use lance::dataset::cleanup::RemovalStats;
3031 use lance::dataset::optimize::{compact_files, CompactionMetrics, IndexRemapperOptions};
@@ -2023,28 +2024,28 @@
20232024 async fn list_indices(&self) -> Result<Vec<IndexConfig>> {
20242025 let dataset = self.dataset.get().await?;
20252026 let indices = dataset.load_indices().await?;
2026- indices.iter().map(|idx| {
2027- let mut is_vector = false;
2027+ futures::stream::iter(indices.as_slice()).then(|idx| async {
2028+ let stats = dataset.index_statistics(idx.name.as_str()).await?;
2029+ let stats: serde_json::Value = serde_json::from_str(&stats).map_err(|e| Error::Runtime {
2030+ message: format!("error deserializing index statistics: {}", e),
2031+ })?;
2032+ let index_type = stats.get("index_type").and_then(|v| v.as_str())
2033+ .ok_or_else(|| Error::Runtime {
2034+ message: "index statistics was missing index type".to_string(),
2035+ })?;
2036+ let index_type: crate::index::IndexType = index_type.parse().map_err(|e| Error::Runtime {
2037+ message: format!("error parsing index type: {}", e),
2038+ })?;
2039+
20282040 let mut columns = Vec::with_capacity(idx.fields.len());
20292041 for field_id in &idx.fields {
20302042 let field = dataset.schema().field_by_id(*field_id).ok_or_else(|| Error::Runtime { message: format!("The index with name {} and uuid {} referenced a field with id {} which does not exist in the schema", idx.name, idx.uuid, field_id) })?;
2031- if field.data_type().is_nested() {
2032- // Temporary hack to determine if an index is scalar or vector
2033- // Should be removed in https://github.com/lancedb/lance/issues/2039
2034- is_vector = true;
2035- }
20362043 columns.push(field.name.clone());
20372044 }
20382045
2039- let index_type = if is_vector {
2040- crate::index::IndexType::IvfPq
2041- } else {
2042- crate::index::IndexType::BTree
2043- };
2044-
20452046 let name = idx.name.clone();
20462047 Ok(IndexConfig { index_type, columns, name })
2047- }).collect::<Result<Vec<_>>>()
2048+ }).try_collect::<Vec<_>>().await
20482049 }
20492050
20502051 fn dataset_uri(&self) -> &str {
@@ -2803,7 +2804,7 @@
28032804 let index_configs = table.list_indices().await.unwrap();
28042805 assert_eq!(index_configs.len(), 1);
28052806 let index = index_configs.into_iter().next().unwrap();
2806- assert_eq!(index.index_type, crate::index::IndexType::IvfPq);
2807+ assert_eq!(index.index_type, crate::index::IndexType::IvfHnswSq);
28072808 assert_eq!(index.columns, vec!["embeddings".to_string()]);
28082809 assert_eq!(table.count_rows(None).await.unwrap(), 512);
28092810 assert_eq!(table.name(), "test");
@@ -2867,7 +2868,7 @@
28672868 let index_configs = table.list_indices().await.unwrap();
28682869 assert_eq!(index_configs.len(), 1);
28692870 let index = index_configs.into_iter().next().unwrap();
2870- assert_eq!(index.index_type, crate::index::IndexType::IvfPq);
2871+ assert_eq!(index.index_type, crate::index::IndexType::IvfHnswPq);
28712872 assert_eq!(index.columns, vec!["embeddings".to_string()]);
28722873 assert_eq!(table.count_rows(None).await.unwrap(), 512);
28732874 assert_eq!(table.name(), "test");