| 1 | # Approximate Nearest Neighbor (ANN) Indexes |
| 2 | |
| 3 | An ANN or a vector index is a data structure specifically designed to efficiently organize and |
| 4 | search vector data based on their similarity via the chosen distance metric. |
| 5 | By constructing a vector index, the search space is effectively narrowed down, avoiding the need |
| 6 | for brute-force scanning of the entire vector space. |
| 7 | A vector index is faster but less accurate than exhaustive search (kNN or flat search). |
| 8 | LanceDB provides many parameters to fine-tune the index's size, the speed of queries, and the accuracy of results. |
| 9 | |
| 10 | ## Disk-based Index |
| 11 | |
| 12 | Lance provides an `IVF_PQ` disk-based index. It uses **Inverted File Index (IVF)** to first divide |
| 13 | the dataset into `N` partitions, and then applies **Product Quantization** to compress vectors in each partition. |
| 14 | See the [indexing](concepts/index_ivfpq.md) concepts guide for more information on how this works. |
| 15 | |
| 16 | ## Creating an IVF_PQ Index |
| 17 | |
| 18 | Lance supports `IVF_PQ` index type by default. |
| 19 | |
| 20 | === "Python" |
| 21 | |
| 22 | Creating indexes is done via the [create_index](https://lancedb.github.io/lancedb/python/#lancedb.table.LanceTable.create_index) method. |
| 23 | |
| 24 | ```python |
| 25 | import lancedb |
| 26 | import numpy as np |
| 27 | uri = "data/sample-lancedb" |
| 28 | db = lancedb.connect(uri) |
| 29 | |
| 30 | # Create 10,000 sample vectors |
| 31 | data = [{"vector": row, "item": f"item {i}"} |
| 32 | for i, row in enumerate(np.random.random((10_000, 1536)).astype('float32'))] |
| 33 | |
| 34 | # Add the vectors to a table |
| 35 | tbl = db.create_table("my_vectors", data=data) |
| 36 | |
| 37 | # Create and train the index - you need to have enough data in the table for an effective training step |
| 38 | tbl.create_index(num_partitions=256, num_sub_vectors=96) |
| 39 | ``` |
| 40 | |
| 41 | === "TypeScript" |
| 42 | |
| 43 | === "@lancedb/lancedb" |
| 44 | |
| 45 | Creating indexes is done via the [lancedb.Table.createIndex](../js/classes/Table.md/#createIndex) method. |
| 46 | |
| 47 | ```typescript |
| 48 | --8<--- "nodejs/examples/ann_indexes.ts:import" |
| 49 | |
| 50 | --8<-- "nodejs/examples/ann_indexes.ts:ingest" |
| 51 | ``` |
| 52 | |
| 53 | === "vectordb (deprecated)" |
| 54 | |
| 55 | Creating indexes is done via the [lancedb.Table.createIndex](../javascript/interfaces/Table.md/#createIndex) method. |
| 56 | |
| 57 | ```typescript |
| 58 | --8<--- "docs/src/ann_indexes.ts:import" |
| 59 | |
| 60 | --8<-- "docs/src/ann_indexes.ts:ingest" |
| 61 | ``` |
| 62 | |
| 63 | === "Rust" |
| 64 | |
| 65 | ```rust |
| 66 | --8<-- "rust/lancedb/examples/ivf_pq.rs:create_index" |
| 67 | ``` |
| 68 | |
| 69 | IVF_PQ index parameters are more fully defined in the [crate docs](https://docs.rs/lancedb/latest/lancedb/index/vector/struct.IvfPqIndexBuilder.html). |
| 70 | |
| 71 | The following IVF_PQ paramters can be specified: |
| 72 | |
| 73 | - **distance_type**: The distance metric to use. By default it uses euclidean distance "`L2`". |
| 74 | We also support "cosine" and "dot" distance as well. |
| 75 | - **num_partitions**: The number of partitions in the index. The default is the square root |
| 76 | of the number of rows. |
| 77 | |
| 78 | !!! note |
| 79 | |
| 80 | In the synchronous python SDK and node's `vectordb` the default is 256. This default has |
| 81 | changed in the asynchronous python SDK and node's `lancedb`. |
| 82 | |
| 83 | - **num_sub_vectors**: The number of sub-vectors (M) that will be created during Product Quantization (PQ). |
| 84 | For D dimensional vector, it will be divided into `M` subvectors with dimension `D/M`, each of which is replaced by |
| 85 | a single PQ code. The default is the dimension of the vector divided by 16. |
| 86 | |
| 87 | !!! note |
| 88 | |
| 89 | In the synchronous python SDK and node's `vectordb` the default is currently 96. This default has |
| 90 | changed in the asynchronous python SDK and node's `lancedb`. |
| 91 | |
| 92 | <figure markdown> |
| 93 |  |
| 94 | <figcaption>IVF_PQ index with <code>num_partitions=2, num_sub_vectors=4</code></figcaption> |
| 95 | </figure> |
| 96 | |
| 97 | ### Use GPU to build vector index |
| 98 | |
| 99 | Lance Python SDK has experimental GPU support for creating IVF index. |
| 100 | Using GPU for index creation requires [PyTorch>2.0](https://pytorch.org/) being installed. |
| 101 | |
| 102 | You can specify the GPU device to train IVF partitions via |
| 103 | |
| 104 | - **accelerator**: Specify to `cuda` or `mps` (on Apple Silicon) to enable GPU training. |
| 105 | |
| 106 | === "Linux" |
| 107 | |
| 108 | <!-- skip-test --> |
| 109 | ``` { .python .copy } |
| 110 | # Create index using CUDA on Nvidia GPUs. |
| 111 | tbl.create_index( |
| 112 | num_partitions=256, |
| 113 | num_sub_vectors=96, |
| 114 | accelerator="cuda" |
| 115 | ) |
| 116 | ``` |
| 117 | |
| 118 | === "MacOS" |
| 119 | |
| 120 | <!-- skip-test --> |
| 121 | ```python |
| 122 | # Create index using MPS on Apple Silicon. |
| 123 | tbl.create_index( |
| 124 | num_partitions=256, |
| 125 | num_sub_vectors=96, |
| 126 | accelerator="mps" |
| 127 | ) |
| 128 | ``` |
| 129 | |
| 130 | Troubleshooting: |
| 131 | |
| 132 | If you see `AssertionError: Torch not compiled with CUDA enabled`, you need to [install |
| 133 | PyTorch with CUDA support](https://pytorch.org/get-started/locally/). |
| 134 | |
| 135 | ## Querying an ANN Index |
| 136 | |
| 137 | Querying vector indexes is done via the [search](https://lancedb.github.io/lancedb/python/#lancedb.table.LanceTable.search) function. |
| 138 | |
| 139 | There are a couple of parameters that can be used to fine-tune the search: |
| 140 | |
| 141 | - **limit** (default: 10): The amount of results that will be returned |
| 142 | - **nprobes** (default: 20): The number of probes used. A higher number makes search more accurate but also slower.<br/> |
| 143 | Most of the time, setting nprobes to cover 5-10% of the dataset should achieve high recall with low latency.<br/> |
| 144 | e.g., for 1M vectors divided up into 256 partitions, nprobes should be set to ~20-40.<br/> |
| 145 | Note: nprobes is only applicable if an ANN index is present. If specified on a table without an ANN index, it is ignored. |
| 146 | - **refine_factor** (default: None): Refine the results by reading extra elements and re-ranking them in memory.<br/> |
| 147 | A higher number makes search more accurate but also slower. If you find the recall is less than ideal, try refine_factor=10 to start.<br/> |
| 148 | e.g., for 1M vectors divided into 256 partitions, if you're looking for top 20, then refine_factor=200 reranks the whole partition.<br/> |
| 149 | Note: refine_factor is only applicable if an ANN index is present. If specified on a table without an ANN index, it is ignored. |
| 150 | |
| 151 | === "Python" |
| 152 | |
| 153 | ```python |
| 154 | tbl.search(np.random.random((1536))) \ |
| 155 | .limit(2) \ |
| 156 | .nprobes(20) \ |
| 157 | .refine_factor(10) \ |
| 158 | .to_pandas() |
| 159 | ``` |
| 160 | |
| 161 | ```text |
| 162 | vector item _distance |
| 163 | 0 [0.44949695, 0.8444449, 0.06281311, 0.23338133... item 1141 103.575333 |
| 164 | 1 [0.48587373, 0.269207, 0.15095535, 0.65531915,... item 3953 108.393867 |
| 165 | ``` |
| 166 | |
| 167 | === "TypeScript" |
| 168 | |
| 169 | === "@lancedb/lancedb" |
| 170 | |
| 171 | ```typescript |
| 172 | --8<-- "nodejs/examples/ann_indexes.ts:search1" |
| 173 | ``` |
| 174 | |
| 175 | === "vectordb (deprecated)" |
| 176 | |
| 177 | ```typescript |
| 178 | --8<-- "docs/src/ann_indexes.ts:search1" |
| 179 | ``` |
| 180 | |
| 181 | === "Rust" |
| 182 | |
| 183 | ```rust |
| 184 | --8<-- "rust/lancedb/examples/ivf_pq.rs:search1" |
| 185 | ``` |
| 186 | |
| 187 | Vector search options are more fully defined in the [crate docs](https://docs.rs/lancedb/latest/lancedb/query/struct.Query.html#method.nearest_to). |
| 188 | |
| 189 | The search will return the data requested in addition to the distance of each item. |
| 190 | |
| 191 | ### Filtering (where clause) |
| 192 | |
| 193 | You can further filter the elements returned by a search using a where clause. |
| 194 | |
| 195 | === "Python" |
| 196 | |
| 197 | ```python |
| 198 | tbl.search(np.random.random((1536))).where("item != 'item 1141'").to_pandas() |
| 199 | ``` |
| 200 | |
| 201 | === "TypeScript" |
| 202 | |
| 203 | === "@lancedb/lancedb" |
| 204 | |
| 205 | ```typescript |
| 206 | --8<-- "nodejs/examples/ann_indexes.ts:search2" |
| 207 | ``` |
| 208 | |
| 209 | === "vectordb (deprecated)" |
| 210 | |
| 211 | ```javascript |
| 212 | --8<-- "docs/src/ann_indexes.ts:search2" |
| 213 | ``` |
| 214 | |
| 215 | ### Projections (select clause) |
| 216 | |
| 217 | You can select the columns returned by the query using a select clause. |
| 218 | |
| 219 | === "Python" |
| 220 | |
| 221 | ```python |
| 222 | tbl.search(np.random.random((1536))).select(["vector"]).to_pandas() |
| 223 | ``` |
| 224 | |
| 225 | |
| 226 | ```text |
| 227 | vector _distance |
| 228 | 0 [0.30928212, 0.022668175, 0.1756372, 0.4911822... 93.971092 |
| 229 | 1 [0.2525465, 0.01723831, 0.261568, 0.002007689,... 95.173485 |
| 230 | ... |
| 231 | ``` |
| 232 | |
| 233 | === "TypeScript" |
| 234 | |
| 235 | === "@lancedb/lancedb" |
| 236 | |
| 237 | ```typescript |
| 238 | --8<-- "nodejs/examples/ann_indexes.ts:search3" |
| 239 | ``` |
| 240 | |
| 241 | === "vectordb (deprecated)" |
| 242 | |
| 243 | ```typescript |
| 244 | --8<-- "docs/src/ann_indexes.ts:search3" |
| 245 | ``` |
| 246 | |
| 247 | ## FAQ |
| 248 | |
| 249 | ### Why do I need to manually create an index? |
| 250 | |
| 251 | Currently, LanceDB does _not_ automatically create the ANN index. |
| 252 | LanceDB is well-optimized for kNN (exhaustive search) via a disk-based index. For many use-cases, |
| 253 | datasets of the order of ~100K vectors don't require index creation. If you can live with up to |
| 254 | 100ms latency, skipping index creation is a simpler workflow while guaranteeing 100% recall. |
| 255 | |
| 256 | ### When is it necessary to create an ANN vector index? |
| 257 | |
| 258 | `LanceDB` comes out-of-the-box with highly optimized SIMD code for computing vector similarity. |
| 259 | In our benchmarks, computing distances for 100K pairs of 1K dimension vectors takes **less than 20ms**. |
| 260 | We observe that for small datasets (~100K rows) or for applications that can accept 100ms latency, |
| 261 | vector indices are usually not necessary. |
| 262 | |
| 263 | For large-scale or higher dimension vectors, it can beneficial to create vector index for performance. |
| 264 | |
| 265 | ### How big is my index, and how many memory will it take? |
| 266 | |
| 267 | In LanceDB, all vector indices are **disk-based**, meaning that when responding to a vector query, only the relevant pages from the index file are loaded from disk and cached in memory. Additionally, each sub-vector is usually encoded into 1 byte PQ code. |
| 268 | |
| 269 | For example, with a 1024-dimension dataset, if we choose `num_sub_vectors=64`, each sub-vector has `1024 / 64 = 16` float32 numbers. |
| 270 | Product quantization can lead to approximately `16 * sizeof(float32) / 1 = 64` times of space reduction. |
| 271 | |
| 272 | ### How to choose `num_partitions` and `num_sub_vectors` for `IVF_PQ` index? |
| 273 | |
| 274 | `num_partitions` is used to decide how many partitions the first level `IVF` index uses. |
| 275 | Higher number of partitions could lead to more efficient I/O during queries and better accuracy, but it takes much more time to train. |
| 276 | On `SIFT-1M` dataset, our benchmark shows that keeping each partition 1K-4K rows lead to a good latency / recall. |
| 277 | |
| 278 | `num_sub_vectors` specifies how many Product Quantization (PQ) short codes to generate on each vector. Because |
| 279 | PQ is a lossy compression of the original vector, a higher `num_sub_vectors` usually results in |
| 280 | less space distortion, and thus yields better accuracy. However, a higher `num_sub_vectors` also causes heavier I/O and |
| 281 | more PQ computation, and thus, higher latency. `dimension / num_sub_vectors` should be a multiple of 8 for optimum SIMD efficiency. |