Elffuss BraidHub

kikocis/lancedb public

feat: remote index stats (#1702)

BREAKING CHANGE: the return value of `index_stats` method has changed
and all `index_stats` APIs now take index name instead of UUID. Also
several deprecated index statistics methods were removed.

* Removes deprecated methods for individual index statistics
* Aligns public `IndexStatistics` struct with API response from LanceDB
Cloud.
* Implements `index_stats` for remote Rust SDK and Python async API.
Changeset48defa119d6594291881690a2ceb3588b8866ddd6dbcec4fce061a9580210d8a
AuthorWill Jones <willjones127@gmail.com> · 2024-09-27 12:10 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-27 12:10 -07:00
Parentsef299fdfbf7f

Browse the files at this changeset

16 files changed

modified node/src/index.ts +3 −3
@@ -724,9 +724,9 @@
724724 export interface IndexStats {
725725 numIndexedRows: number | null
726726 numUnindexedRows: number | null
727- indexType: string | null
728- distanceType: string | null
729- completedAt: string | null
727+ indexType: string
728+ distanceType?: string
729+ numIndices?: number
730730 }
731731
732732 /**
modified node/src/query.ts +1 −1
@@ -112,7 +112,7 @@
112112 return this
113113 }
114114
115- /**
115+ /**
116116 * Skip searching un-indexed data. This can make search faster, but will miss
117117 * any data that is not yet indexed.
118118 */
modified node/src/remote/client.ts +1 −1
@@ -17,7 +17,7 @@
1717 import { tableFromIPC, type Table as ArrowTable } from 'apache-arrow'
1818
1919 import { type RemoteResponse, type RemoteRequest, Method } from '../middleware'
20-import { MetricType } from '..'
20+import type { MetricType } from '..'
2121
2222 interface HttpLancedbClientMiddleware {
2323 onRemoteRequest(
modified node/src/remote/index.ts +1 −2
@@ -526,8 +526,7 @@
526526 numIndexedRows: body?.num_indexed_rows,
527527 numUnindexedRows: body?.num_unindexed_rows,
528528 indexType: body?.index_type,
529- distanceType: body?.distance_type,
530- completedAt: body?.completed_at
529+ distanceType: body?.distance_type
531530 }
532531 }
533532
modified node/src/test/test.ts +4 −1
@@ -888,9 +888,12 @@
888888 expect(indices[0].columns).to.have.lengthOf(1);
889889 expect(indices[0].columns[0]).to.equal("vector");
890890
891- const stats = await table.indexStats(indices[0].uuid);
891+ const stats = await table.indexStats(indices[0].name);
892892 expect(stats.numIndexedRows).to.equal(300);
893893 expect(stats.numUnindexedRows).to.equal(0);
894+ expect(stats.indexType).to.equal("IVF_PQ");
895+ expect(stats.distanceType).to.equal("l2");
896+ expect(stats.numIndices).to.equal(1);
894897 }).timeout(50_000);
895898 });
896899
modified nodejs/__test__/table.test.ts +3 −0
@@ -479,6 +479,9 @@
479479 expect(stats).toBeDefined();
480480 expect(stats?.numIndexedRows).toEqual(300);
481481 expect(stats?.numUnindexedRows).toEqual(0);
482+ expect(stats?.distanceType).toBeUndefined();
483+ expect(stats?.indexType).toEqual("BTREE");
484+ expect(stats?.numIndices).toEqual(1);
482485 });
483486
484487 test("when getting stats on non-existent index", async () => {
modified nodejs/lancedb/index.ts +0 −1
@@ -32,7 +32,6 @@
3232 ColumnAlteration,
3333 ConnectionOptions,
3434 IndexStatistics,
35- IndexMetadata,
3635 IndexConfig,
3736 } from "./native.js";
3837
modified nodejs/src/table.rs +11 −21
@@ -337,7 +337,7 @@
337337
338338 #[napi(catch_unwind)]
339339 pub async fn index_stats(&self, index_name: String) -> napi::Result<Option<IndexStatistics>> {
340- let tbl = self.inner_ref()?.as_native().unwrap();
340+ let tbl = self.inner_ref()?;
341341 let stats = tbl.index_stats(&index_name).await.default_error()?;
342342 Ok(stats.map(IndexStatistics::from))
343343 }
@@ -480,32 +480,22 @@
480480 /// The number of rows not indexed
481481 pub num_unindexed_rows: f64,
482482 /// The type of the index
483- pub index_type: Option<String>,
484- /// The metadata for each index
485- pub indices: Vec<IndexMetadata>,
483+ pub index_type: String,
484+ /// The type of the distance function used by the index. This is only
485+ /// present for vector indices. Scalar and full text search indices do
486+ /// not have a distance function.
487+ pub distance_type: Option<String>,
488+ /// The number of parts this index is split into.
489+ pub num_indices: Option<u32>,
486490 }
487491 impl From<lancedb::index::IndexStatistics> for IndexStatistics {
488492 fn from(value: lancedb::index::IndexStatistics) -> Self {
489493 Self {
490494 num_indexed_rows: value.num_indexed_rows as f64,
491495 num_unindexed_rows: value.num_unindexed_rows as f64,
492- index_type: value.index_type.map(|t| format!("{:?}", t)),
493- indices: value.indices.into_iter().map(Into::into).collect(),
494- }
495- }
496-}
497-
498-#[napi(object)]
499-pub struct IndexMetadata {
500- pub metric_type: Option<String>,
501- pub index_type: Option<String>,
502-}
503-
504-impl From<lancedb::index::IndexMetadata> for IndexMetadata {
505- fn from(value: lancedb::index::IndexMetadata) -> Self {
506- Self {
507- metric_type: value.metric_type,
508- index_type: value.index_type,
496+ index_type: value.index_type.to_string(),
497+ distance_type: value.distance_type.map(|d| d.to_string()),
498+ num_indices: value.num_indices,
509499 }
510500 }
511501 }
modified python/python/lancedb/table.py +48 −0
@@ -2683,6 +2683,26 @@
26832683 """
26842684 return await self._inner.list_indices()
26852685
2686+ async def index_stats(self, index_name: str) -> Optional[IndexStatistics]:
2687+ """
2688+ Retrieve statistics about an index
2689+
2690+ Parameters
2691+ ----------
2692+ index_name: str
2693+ The name of the index to retrieve statistics for
2694+
2695+ Returns
2696+ -------
2697+ IndexStatistics or None
2698+ The statistics about the index. Returns None if the index does not exist.
2699+ """
2700+ stats = await self._inner.index_stats(index_name)
2701+ if stats is None:
2702+ return None
2703+ else:
2704+ return IndexStatistics(**stats)
2705+
26862706 async def uses_v2_manifest_paths(self) -> bool:
26872707 """
26882708 Check if the table is using the new v2 manifest paths.
@@ -2713,3 +2733,31 @@
27132733 to check if the table is already using the new path style.
27142734 """
27152735 await self._inner.migrate_manifest_paths_v2()
2736+
2737+
2738+@dataclass
2739+class IndexStatistics:
2740+ """
2741+ Statistics about an index.
2742+
2743+ Attributes
2744+ ----------
2745+ num_indexed_rows: int
2746+ The number of rows that are covered by this index.
2747+ num_unindexed_rows: int
2748+ The number of rows that are not covered by this index.
2749+ index_type: str
2750+ The type of index that was created.
2751+ distance_type: Optional[str]
2752+ The distance type used by the index.
2753+ num_indices: Optional[int]
2754+ The number of parts the index is split into.
2755+ """
2756+
2757+ num_indexed_rows: int
2758+ num_unindexed_rows: int
2759+ index_type: Literal[
2760+ "IVF_PQ", "IVF_HNSW_PQ", "IVF_HNSW_SQ", "FTS", "BTREE", "BITMAP", "LABEL_LIST"
2761+ ]
2762+ distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
2763+ num_indices: Optional[int] = None
modified python/python/tests/test_index.py +17 −0
@@ -66,6 +66,15 @@
6666 # TODO: Fix via https://github.com/lancedb/lance/issues/2039
6767 # indices = await some_table.list_indices()
6868 # assert str(indices) == '[Index(Bitmap, columns=["id"])]'
69+ indices = await some_table.list_indices()
70+ assert len(indices) == 1
71+ index_name = indices[0].name
72+ stats = await some_table.index_stats(index_name)
73+ assert stats.index_type == "BITMAP"
74+ assert stats.distance_type is None
75+ assert stats.num_indexed_rows == await some_table.count_rows()
76+ assert stats.num_unindexed_rows == 0
77+ assert stats.num_indices == 1
6978
7079
7180 @pytest.mark.asyncio
@@ -91,6 +100,14 @@
91100 assert len(indices) == 1
92101 assert indices[0].index_type == "IvfPq"
93102 assert indices[0].columns == ["vector"]
103+ assert indices[0].name == "vector_idx"
104+
105+ stats = await some_table.index_stats("vector_idx")
106+ assert stats.index_type == "IVF_PQ"
107+ assert stats.distance_type == "l2"
108+ assert stats.num_indexed_rows == await some_table.count_rows()
109+ assert stats.num_unindexed_rows == 0
110+ assert stats.num_indices == 1
94111
95112
96113 @pytest.mark.asyncio
modified python/src/index.rs +3 −0
@@ -200,6 +200,8 @@
200200 /// Currently this is always a list of size 1. In the future there may
201201 /// be more columns to represent composite indices.
202202 pub columns: Vec<String>,
203+ /// Name of the index.
204+ pub name: String,
203205 }
204206
205207 #[pymethods]
@@ -215,6 +217,7 @@
215217 Self {
216218 index_type,
217219 columns: value.columns,
220+ name: value.name,
218221 }
219222 }
220223 }
modified python/src/table.rs +29 −2
@@ -8,8 +8,8 @@
88 use pyo3::{
99 exceptions::{PyRuntimeError, PyValueError},
1010 pyclass, pymethods,
11- types::{PyDict, PyString},
12- Bound, PyAny, PyRef, PyResult, Python,
11+ types::{PyDict, PyDictMethods, PyString},
12+ Bound, PyAny, PyRef, PyResult, Python, ToPyObject,
1313 };
1414 use pyo3_asyncio_0_21::tokio::future_into_py;
1515
@@ -204,6 +204,33 @@
204204 })
205205 }
206206
207+ pub fn index_stats(self_: PyRef<'_, Self>, index_name: String) -> PyResult<Bound<'_, PyAny>> {
208+ let inner = self_.inner_ref()?.clone();
209+ future_into_py(self_.py(), async move {
210+ let stats = inner.index_stats(&index_name).await.infer_error()?;
211+ if let Some(stats) = stats {
212+ Python::with_gil(|py| {
213+ let dict = PyDict::new_bound(py);
214+ dict.set_item("num_indexed_rows", stats.num_indexed_rows)?;
215+ dict.set_item("num_unindexed_rows", stats.num_unindexed_rows)?;
216+ dict.set_item("index_type", stats.index_type.to_string())?;
217+
218+ if let Some(distance_type) = stats.distance_type {
219+ dict.set_item("distance_type", distance_type.to_string())?;
220+ }
221+
222+ if let Some(num_indices) = stats.num_indices {
223+ dict.set_item("num_indices", num_indices)?;
224+ }
225+
226+ Ok(Some(dict.to_object(py)))
227+ })
228+ } else {
229+ Ok(None)
230+ }
231+ })
232+ }
233+
207234 pub fn __repr__(&self) -> String {
208235 match &self.inner {
209236 None => format!("ClosedTable({})", self.name),
modified rust/ffi/node/src/table.rs +21 −28
@@ -470,49 +470,42 @@
470470 Ok(promise)
471471 }
472472
473- #[allow(deprecated)]
474473 pub(crate) fn js_index_stats(mut cx: FunctionContext) -> JsResult<JsPromise> {
475474 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
476475 let rt = runtime(&mut cx)?;
477476 let (deferred, promise) = cx.promise();
478- let index_uuid = cx.argument::<JsString>(0)?.value(&mut cx);
477+ let index_name = cx.argument::<JsString>(0)?.value(&mut cx);
479478 let channel = cx.channel();
480479 let table = js_table.table.clone();
481480
482481 rt.spawn(async move {
483- let load_stats = futures::try_join!(
484- table.as_native().unwrap().count_indexed_rows(&index_uuid),
485- table.as_native().unwrap().count_unindexed_rows(&index_uuid)
486- );
482+ let load_stats = table.index_stats(index_name).await;
487483
488484 deferred.settle_with(&channel, move |mut cx| {
489- let (indexed_rows, unindexed_rows) = load_stats.or_throw(&mut cx)?;
485+ let stats = load_stats.or_throw(&mut cx)?;
490486
491- let output = JsObject::new(&mut cx);
492-
493- match indexed_rows {
494- Some(x) => {
495- let i = cx.number(x as f64);
496- output.set(&mut cx, "numIndexedRows", i)?;
487+ if let Some(stats) = stats {
488+ let output = JsObject::new(&mut cx);
489+ let num_indexed_rows = cx.number(stats.num_indexed_rows as f64);
490+ output.set(&mut cx, "numIndexedRows", num_indexed_rows)?;
491+ let num_unindexed_rows = cx.number(stats.num_unindexed_rows as f64);
492+ output.set(&mut cx, "numUnindexedRows", num_unindexed_rows)?;
493+ if let Some(distance_type) = stats.distance_type {
494+ let distance_type = cx.string(distance_type.to_string());
495+ output.set(&mut cx, "distanceType", distance_type)?;
497496 }
498- None => {
499- let null = cx.null();
500- output.set(&mut cx, "numIndexedRows", null)?;
501- }
502- };
497+ let index_type = cx.string(stats.index_type.to_string());
498+ output.set(&mut cx, "indexType", index_type)?;
503499
504- match unindexed_rows {
505- Some(x) => {
506- let i = cx.number(x as f64);
507- output.set(&mut cx, "numUnindexedRows", i)?;
508- }
509- None => {
510- let null = cx.null();
511- output.set(&mut cx, "numUnindexedRows", null)?;
500+ if let Some(num_indices) = stats.num_indices {
501+ let num_indices = cx.number(num_indices as f64);
502+ output.set(&mut cx, "numIndices", num_indices)?;
512503 }
513- };
514504
515- Ok(output)
505+ Ok(output.as_value(&mut cx))
506+ } else {
507+ Ok(JsNull::new(&mut cx).as_value(&mut cx))
508+ }
516509 })
517510 });
518511
modified rust/lancedb/src/index.rs +53 −7
@@ -18,7 +18,7 @@
1818 use serde::Deserialize;
1919 use serde_with::skip_serializing_none;
2020
21-use crate::{table::TableInternal, Result};
21+use crate::{table::TableInternal, DistanceType, Result};
2222
2323 use self::{
2424 scalar::{BTreeIndexBuilder, BitmapIndexBuilder, LabelListIndexBuilder},
@@ -102,19 +102,42 @@
102102 }
103103 }
104104
105-#[derive(Debug, Clone, PartialEq)]
105+#[derive(Debug, Clone, PartialEq, Deserialize)]
106106 pub enum IndexType {
107107 // Vector
108+ #[serde(alias = "IVF_PQ")]
108109 IvfPq,
110+ #[serde(alias = "IVF_HNSW_PQ")]
109111 IvfHnswPq,
112+ #[serde(alias = "IVF_HNSW_SQ")]
110113 IvfHnswSq,
111114 // Scalar
115+ #[serde(alias = "BTREE")]
112116 BTree,
117+ #[serde(alias = "BITMAP")]
113118 Bitmap,
119+ #[serde(alias = "LABEL_LIST")]
114120 LabelList,
121+ // FTS
122+ FTS,
123+}
124+
125+impl std::fmt::Display for IndexType {
126+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
127+ match self {
128+ Self::IvfPq => write!(f, "IVF_PQ"),
129+ Self::IvfHnswPq => write!(f, "IVF_HNSW_PQ"),
130+ Self::IvfHnswSq => write!(f, "IVF_HNSW_SQ"),
131+ Self::BTree => write!(f, "BTREE"),
132+ Self::Bitmap => write!(f, "BITMAP"),
133+ Self::LabelList => write!(f, "LABEL_LIST"),
134+ Self::FTS => write!(f, "FTS"),
135+ }
136+ }
115137 }
116138
117139 /// A description of an index currently configured on a column
140+#[derive(Debug, PartialEq, Clone)]
118141 pub struct IndexConfig {
119142 /// The name of the index
120143 pub name: String,
@@ -129,16 +152,39 @@
129152
130153 #[skip_serializing_none]
131154 #[derive(Debug, Deserialize)]
132-pub struct IndexMetadata {
133- pub metric_type: Option<String>,
134- pub index_type: Option<String>,
155+pub(crate) struct IndexMetadata {
156+ pub metric_type: Option<DistanceType>,
157+ // Sometimes the index type is provided at this level.
158+ pub index_type: Option<IndexType>,
135159 }
136160
161+// This struct is used to deserialize the JSON data returned from the Lance API
162+// Dataset::index_statistics().
137163 #[skip_serializing_none]
138164 #[derive(Debug, Deserialize)]
139-pub struct IndexStatistics {
165+pub(crate) struct IndexStatisticsImpl {
140166 pub num_indexed_rows: usize,
141167 pub num_unindexed_rows: usize,
142- pub index_type: Option<String>,
143168 pub indices: Vec<IndexMetadata>,
169+ // Sometimes, the index type is provided at this level.
170+ pub index_type: Option<IndexType>,
171+ pub num_indices: Option<u32>,
172+}
173+
174+#[skip_serializing_none]
175+#[derive(Debug, Deserialize, PartialEq)]
176+pub struct IndexStatistics {
177+ /// The number of rows in the table that are covered by this index.
178+ pub num_indexed_rows: usize,
179+ /// The number of rows in the table that are not covered by this index.
180+ /// These are rows that haven't yet been added to the index.
181+ pub num_unindexed_rows: usize,
182+ /// The type of the index.
183+ pub index_type: IndexType,
184+ /// The distance type used by the index.
185+ ///
186+ /// This is only present for vector indices.
187+ pub distance_type: Option<DistanceType>,
188+ /// The number of parts this index is split into.
189+ pub num_indices: Option<u32>,
144190 }
modified rust/lancedb/src/remote/table.rs +67 −1
@@ -1,6 +1,7 @@
11 use std::sync::{Arc, Mutex};
22
33 use crate::index::Index;
4+use crate::index::IndexStatistics;
45 use crate::query::Select;
56 use crate::table::AddDataMode;
67 use crate::utils::{supported_btree_data_type, supported_vector_data_type};
@@ -523,6 +524,26 @@
523524 message: "list_indices is not yet supported.".into(),
524525 })
525526 }
527+ async fn index_stats(&self, index_name: &str) -> Result<Option<IndexStatistics>> {
528+ let request = self
529+ .client
530+ .post(&format!("/table/{}/index/{}/stats/", self.name, index_name));
531+ let response = self.client.send(request).await?;
532+
533+ if response.status() == StatusCode::NOT_FOUND {
534+ return Ok(None);
535+ }
536+
537+ let response = self.check_table_response(response).await?;
538+
539+ let body = response.text().await?;
540+
541+ let stats = serde_json::from_str(&body).map_err(|e| Error::Http {
542+ message: format!("Failed to parse index statistics: {}", e),
543+ })?;
544+
545+ Ok(Some(stats))
546+ }
526547 async fn table_definition(&self) -> Result<TableDefinition> {
527548 Err(Error::NotSupported {
528549 message: "table_definition is not supported on LanceDB cloud.".into(),
@@ -582,7 +603,7 @@
582603 use reqwest::Body;
583604
584605 use crate::{
585- index::{vector::IvfPqIndexBuilder, Index},
606+ index::{vector::IvfPqIndexBuilder, Index, IndexStatistics, IndexType},
586607 query::{ExecutableQuery, QueryBase},
587608 DistanceType, Error, Table,
588609 };
@@ -1152,4 +1173,49 @@
11521173 table.create_index(&["a"], index).execute().await.unwrap();
11531174 }
11541175 }
1176+
1177+ #[tokio::test]
1178+ async fn test_index_stats() {
1179+ let table = Table::new_with_handler("my_table", |request| {
1180+ assert_eq!(request.method(), "POST");
1181+ assert_eq!(
1182+ request.url().path(),
1183+ "/table/my_table/index/my_index/stats/"
1184+ );
1185+
1186+ let response_body = serde_json::json!({
1187+ "num_indexed_rows": 100000,
1188+ "num_unindexed_rows": 0,
1189+ "index_type": "IVF_PQ",
1190+ "distance_type": "l2"
1191+ });
1192+ let response_body = serde_json::to_string(&response_body).unwrap();
1193+
1194+ http::Response::builder()
1195+ .status(200)
1196+ .body(response_body)
1197+ .unwrap()
1198+ });
1199+ let indices = table.index_stats("my_index").await.unwrap().unwrap();
1200+ let expected = IndexStatistics {
1201+ num_indexed_rows: 100000,
1202+ num_unindexed_rows: 0,
1203+ index_type: IndexType::IvfPq,
1204+ distance_type: Some(DistanceType::L2),
1205+ num_indices: None,
1206+ };
1207+ assert_eq!(indices, expected);
1208+
1209+ let table = Table::new_with_handler("my_table", |request| {
1210+ assert_eq!(request.method(), "POST");
1211+ assert_eq!(
1212+ request.url().path(),
1213+ "/table/my_table/index/my_index/stats/"
1214+ );
1215+
1216+ http::Response::builder().status(404).body("").unwrap()
1217+ });
1218+ let indices = table.index_stats("my_index").await.unwrap();
1219+ assert!(indices.is_none());
1220+ }
11551221 }
modified rust/lancedb/src/table.rs +73 −237
@@ -47,7 +47,6 @@
4747 use lance_table::io::commit::ManifestNamingScheme;
4848 use log::info;
4949 use serde::{Deserialize, Serialize};
50-use snafu::whatever;
5150
5251 use crate::arrow::IntoArrow;
5352 use crate::connection::NoData;
@@ -58,12 +57,12 @@
5857 suggested_num_partitions_for_hnsw, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder,
5958 IvfPqIndexBuilder, VectorIndex,
6059 };
61-use crate::index::IndexConfig;
6260 use crate::index::IndexStatistics;
6361 use crate::index::{
6462 vector::{suggested_num_partitions, suggested_num_sub_vectors},
6563 Index, IndexBuilder,
6664 };
65+use crate::index::{IndexConfig, IndexStatisticsImpl};
6766 use crate::query::{
6867 IntoQueryVector, Query, QueryExecutionOptions, Select, VectorQuery, DEFAULT_TOP_K,
6968 };
@@ -405,6 +404,7 @@
405404 async fn update(&self, update: UpdateBuilder) -> Result<u64>;
406405 async fn create_index(&self, index: IndexBuilder) -> Result<()>;
407406 async fn list_indices(&self) -> Result<Vec<IndexConfig>>;
407+ async fn index_stats(&self, index_name: &str) -> Result<Option<IndexStatistics>>;
408408 async fn merge_insert(
409409 &self,
410410 params: MergeInsertBuilder,
@@ -962,6 +962,15 @@
962962 pub fn dataset_uri(&self) -> &str {
963963 self.inner.dataset_uri()
964964 }
965+
966+ /// Get statistics about an index.
967+ /// Returns None if the index does not exist.
968+ pub async fn index_stats(
969+ &self,
970+ index_name: impl AsRef<str>,
971+ ) -> Result<Option<IndexStatistics>> {
972+ self.inner.index_stats(index_name.as_ref()).await
973+ }
965974 }
966975
967976 impl From<NativeTable> for Table {
@@ -1250,91 +1259,6 @@
12501259 .await)
12511260 }
12521261
1253- #[deprecated(since = "0.5.2", note = "Please use `index_stats` instead")]
1254- pub async fn count_indexed_rows(&self, index_uuid: &str) -> Result<Option<usize>> {
1255- #[allow(deprecated)]
1256- match self.load_index_stats(index_uuid).await? {
1257- Some(stats) => Ok(Some(stats.num_indexed_rows)),
1258- None => Ok(None),
1259- }
1260- }
1261-
1262- #[deprecated(since = "0.5.2", note = "Please use `index_stats` instead")]
1263- pub async fn count_unindexed_rows(&self, index_uuid: &str) -> Result<Option<usize>> {
1264- #[allow(deprecated)]
1265- match self.load_index_stats(index_uuid).await? {
1266- Some(stats) => Ok(Some(stats.num_unindexed_rows)),
1267- None => Ok(None),
1268- }
1269- }
1270-
1271- #[deprecated(since = "0.5.2", note = "Please use `index_stats` instead")]
1272- pub async fn get_index_type(&self, index_uuid: &str) -> Result<Option<String>> {
1273- #[allow(deprecated)]
1274- match self.load_index_stats(index_uuid).await? {
1275- Some(stats) => Ok(Some(stats.index_type.unwrap_or_default())),
1276- None => Ok(None),
1277- }
1278- }
1279-
1280- #[deprecated(since = "0.5.2", note = "Please use `index_stats` instead")]
1281- pub async fn get_distance_type(&self, index_uuid: &str) -> Result<Option<String>> {
1282- #[allow(deprecated)]
1283- match self.load_index_stats(index_uuid).await? {
1284- Some(stats) => Ok(Some(
1285- stats
1286- .indices
1287- .iter()
1288- .filter_map(|i| i.metric_type.clone())
1289- .collect(),
1290- )),
1291- None => Ok(None),
1292- }
1293- }
1294-
1295- #[deprecated(since = "0.5.2", note = "Please use `index_stats` instead")]
1296- pub async fn load_index_stats(&self, index_uuid: &str) -> Result<Option<IndexStatistics>> {
1297- let index = self
1298- .load_indices()
1299- .await?
1300- .into_iter()
1301- .find(|i| i.index_uuid == index_uuid);
1302- if index.is_none() {
1303- return Ok(None);
1304- }
1305- let dataset = self.dataset.get().await?;
1306- let index_stats = dataset.index_statistics(&index.unwrap().index_name).await?;
1307- let index_stats: IndexStatistics = whatever!(
1308- serde_json::from_str(&index_stats),
1309- "error deserializing index statistics {index_stats}",
1310- );
1311-
1312- Ok(Some(index_stats))
1313- }
1314-
1315- /// Get statistics about an index.
1316- /// Returns an error if the index does not exist.
1317- pub async fn index_stats(
1318- &self,
1319- index_name: impl AsRef<str>,
1320- ) -> Result<Option<IndexStatistics>> {
1321- let stats = match self
1322- .dataset
1323- .get()
1324- .await?
1325- .index_statistics(index_name.as_ref())
1326- .await
1327- {
1328- Ok(stats) => stats,
1329- Err(lance::error::Error::IndexNotFound { .. }) => return Ok(None),
1330- Err(e) => return Err(Error::from(e)),
1331- };
1332-
1333- serde_json::from_str(&stats).map_err(|e| Error::InvalidInput {
1334- message: format!("error deserializing index statistics: {}", e),
1335- })
1336- }
1337-
13381262 pub async fn load_indices(&self) -> Result<Vec<VectorIndex>> {
13391263 let dataset = self.dataset.get().await?;
13401264 let (indices, mf) = futures::try_join!(dataset.load_indices(), dataset.latest_manifest())?;
@@ -2126,6 +2050,44 @@
21262050 fn dataset_uri(&self) -> &str {
21272051 self.uri.as_str()
21282052 }
2053+
2054+ async fn index_stats(&self, index_name: &str) -> Result<Option<IndexStatistics>> {
2055+ let stats = match self
2056+ .dataset
2057+ .get()
2058+ .await?
2059+ .index_statistics(index_name.as_ref())
2060+ .await
2061+ {
2062+ Ok(stats) => stats,
2063+ Err(lance::error::Error::IndexNotFound { .. }) => return Ok(None),
2064+ Err(e) => return Err(Error::from(e)),
2065+ };
2066+
2067+ let mut stats: IndexStatisticsImpl =
2068+ serde_json::from_str(&stats).map_err(|e| Error::InvalidInput {
2069+ message: format!("error deserializing index statistics: {}", e),
2070+ })?;
2071+
2072+ let first_index = stats.indices.pop().ok_or_else(|| Error::InvalidInput {
2073+ message: "index statistics is empty".to_string(),
2074+ })?;
2075+ // Index type should be present at one of the levels.
2076+ let index_type =
2077+ stats
2078+ .index_type
2079+ .or(first_index.index_type)
2080+ .ok_or_else(|| Error::InvalidInput {
2081+ message: "index statistics was missing index type".to_string(),
2082+ })?;
2083+ Ok(Some(IndexStatistics {
2084+ num_indexed_rows: stats.num_indexed_rows,
2085+ num_unindexed_rows: stats.num_unindexed_rows,
2086+ index_type,
2087+ distance_type: first_index.metric_type,
2088+ num_indices: stats.num_indices,
2089+ }))
2090+ }
21292091 }
21302092
21312093 #[cfg(test)]
@@ -2763,24 +2725,7 @@
27632725
27642726 let table = conn.create_table("test", batches).execute().await.unwrap();
27652727
2766- assert_eq!(
2767- table
2768- .as_native()
2769- .unwrap()
2770- .count_indexed_rows("my_index")
2771- .await
2772- .unwrap(),
2773- None
2774- );
2775- assert_eq!(
2776- table
2777- .as_native()
2778- .unwrap()
2779- .count_unindexed_rows("my_index")
2780- .await
2781- .unwrap(),
2782- None
2783- );
2728+ assert_eq!(table.index_stats("my_index").await.unwrap(), None);
27842729
27852730 table
27862731 .create_index(&["embeddings"], Index::Auto)
@@ -2797,43 +2742,12 @@
27972742 assert_eq!(table.name(), "test");
27982743
27992744 let indices = table.as_native().unwrap().load_indices().await.unwrap();
2800- let index_uuid = &indices[0].index_uuid;
2801- assert_eq!(
2802- table
2803- .as_native()
2804- .unwrap()
2805- .count_indexed_rows(index_uuid)
2806- .await
2807- .unwrap(),
2808- Some(512)
2809- );
2810- assert_eq!(
2811- table
2812- .as_native()
2813- .unwrap()
2814- .count_unindexed_rows(index_uuid)
2815- .await
2816- .unwrap(),
2817- Some(0)
2818- );
2819- assert_eq!(
2820- table
2821- .as_native()
2822- .unwrap()
2823- .get_index_type(index_uuid)
2824- .await
2825- .unwrap(),
2826- Some("IVF_PQ".to_string())
2827- );
2828- assert_eq!(
2829- table
2830- .as_native()
2831- .unwrap()
2832- .get_distance_type(index_uuid)
2833- .await
2834- .unwrap(),
2835- Some(crate::DistanceType::L2.to_string())
2836- );
2745+ let index_name = &indices[0].index_name;
2746+ let stats = table.index_stats(index_name).await.unwrap().unwrap();
2747+ assert_eq!(stats.num_indexed_rows, 512);
2748+ assert_eq!(stats.num_unindexed_rows, 0);
2749+ assert_eq!(stats.index_type, crate::index::IndexType::IvfPq);
2750+ assert_eq!(stats.distance_type, Some(crate::DistanceType::L2));
28372751 }
28382752
28392753 #[tokio::test]
@@ -2876,24 +2790,8 @@
28762790
28772791 let table = conn.create_table("test", batches).execute().await.unwrap();
28782792
2879- assert_eq!(
2880- table
2881- .as_native()
2882- .unwrap()
2883- .count_indexed_rows("my_index")
2884- .await
2885- .unwrap(),
2886- None
2887- );
2888- assert_eq!(
2889- table
2890- .as_native()
2891- .unwrap()
2892- .count_unindexed_rows("my_index")
2893- .await
2894- .unwrap(),
2895- None
2896- );
2793+ let stats = table.index_stats("my_index").await.unwrap();
2794+ assert!(stats.is_none());
28972795
28982796 let index = IvfHnswSqIndexBuilder::default();
28992797 table
@@ -2911,25 +2809,10 @@
29112809 assert_eq!(table.name(), "test");
29122810
29132811 let indices = table.as_native().unwrap().load_indices().await.unwrap();
2914- let index_uuid = &indices[0].index_uuid;
2915- assert_eq!(
2916- table
2917- .as_native()
2918- .unwrap()
2919- .count_indexed_rows(index_uuid)
2920- .await
2921- .unwrap(),
2922- Some(512)
2923- );
2924- assert_eq!(
2925- table
2926- .as_native()
2927- .unwrap()
2928- .count_unindexed_rows(index_uuid)
2929- .await
2930- .unwrap(),
2931- Some(0)
2932- );
2812+ let index_name = &indices[0].index_name;
2813+ let stats = table.index_stats(index_name).await.unwrap().unwrap();
2814+ assert_eq!(stats.num_indexed_rows, 512);
2815+ assert_eq!(stats.num_unindexed_rows, 0);
29332816 }
29342817
29352818 #[tokio::test]
@@ -2971,25 +2854,8 @@
29712854 );
29722855
29732856 let table = conn.create_table("test", batches).execute().await.unwrap();
2974-
2975- assert_eq!(
2976- table
2977- .as_native()
2978- .unwrap()
2979- .count_indexed_rows("my_index")
2980- .await
2981- .unwrap(),
2982- None
2983- );
2984- assert_eq!(
2985- table
2986- .as_native()
2987- .unwrap()
2988- .count_unindexed_rows("my_index")
2989- .await
2990- .unwrap(),
2991- None
2992- );
2857+ let stats = table.index_stats("my_index").await.unwrap();
2858+ assert!(stats.is_none());
29932859
29942860 let index = IvfHnswPqIndexBuilder::default();
29952861 table
@@ -3006,26 +2872,11 @@
30062872 assert_eq!(table.count_rows(None).await.unwrap(), 512);
30072873 assert_eq!(table.name(), "test");
30082874
3009- let indices = table.as_native().unwrap().load_indices().await.unwrap();
3010- let index_uuid = &indices[0].index_uuid;
3011- assert_eq!(
3012- table
3013- .as_native()
3014- .unwrap()
3015- .count_indexed_rows(index_uuid)
3016- .await
3017- .unwrap(),
3018- Some(512)
3019- );
3020- assert_eq!(
3021- table
3022- .as_native()
3023- .unwrap()
3024- .count_unindexed_rows(index_uuid)
3025- .await
3026- .unwrap(),
3027- Some(0)
3028- );
2875+ let indices: Vec<VectorIndex> = table.as_native().unwrap().load_indices().await.unwrap();
2876+ let index_name = &indices[0].index_name;
2877+ let stats = table.index_stats(index_name).await.unwrap().unwrap();
2878+ assert_eq!(stats.num_indexed_rows, 512);
2879+ assert_eq!(stats.num_unindexed_rows, 0);
30292880 }
30302881
30312882 fn create_fixed_size_list<T: Array>(values: T, list_size: i32) -> Result<FixedSizeListArray> {
@@ -3101,25 +2952,10 @@
31012952 assert_eq!(index.columns, vec!["i".to_string()]);
31022953
31032954 let indices = table.as_native().unwrap().load_indices().await.unwrap();
3104- let index_uuid = &indices[0].index_uuid;
3105- assert_eq!(
3106- table
3107- .as_native()
3108- .unwrap()
3109- .count_indexed_rows(index_uuid)
3110- .await
3111- .unwrap(),
3112- Some(1)
3113- );
3114- assert_eq!(
3115- table
3116- .as_native()
3117- .unwrap()
3118- .count_unindexed_rows(index_uuid)
3119- .await
3120- .unwrap(),
3121- Some(0)
3122- );
2955+ let index_name = &indices[0].index_name;
2956+ let stats = table.index_stats(index_name).await.unwrap().unwrap();
2957+ assert_eq!(stats.num_indexed_rows, 1);
2958+ assert_eq!(stats.num_unindexed_rows, 0);
31232959 }
31242960
31252961 #[tokio::test]