| 1 | # Vector Search |
| 2 | |
| 3 | A vector search finds the approximate or exact nearest neighbors to a given query vector. |
| 4 | |
| 5 | - In a recommendation system or search engine, you can find similar records to |
| 6 | the one you searched. |
| 7 | - In LLM and other AI applications, |
| 8 | each data point can be represented by [embeddings generated from existing models](embeddings/index.md), |
| 9 | following which the search returns the most relevant features. |
| 10 | |
| 11 | ## Distance metrics |
| 12 | |
| 13 | Distance metrics are a measure of the similarity between a pair of vectors. |
| 14 | Currently, LanceDB supports the following metrics: |
| 15 | |
| 16 | | Metric | Description | |
| 17 | | -------- | --------------------------------------------------------------------------- | |
| 18 | | `l2` | [Euclidean / L2 distance](https://en.wikipedia.org/wiki/Euclidean_distance) | |
| 19 | | `cosine` | [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity) | |
| 20 | | `dot` | [Dot Production](https://en.wikipedia.org/wiki/Dot_product) | |
| 21 | |
| 22 | ## Exhaustive search (kNN) |
| 23 | |
| 24 | If you do not create a vector index, LanceDB exhaustively scans the _entire_ vector space |
| 25 | and computes the distance to every vector in order to find the exact nearest neighbors. This is effectively a kNN search. |
| 26 | |
| 27 | <!-- Setup Code |
| 28 | ```python |
| 29 | import lancedb |
| 30 | import numpy as np |
| 31 | uri = "data/sample-lancedb" |
| 32 | db = lancedb.connect(uri) |
| 33 | |
| 34 | data = [{"vector": row, "item": f"item {i}"} |
| 35 | for i, row in enumerate(np.random.random((10_000, 1536)).astype('float32'))] |
| 36 | |
| 37 | db.create_table("my_vectors", data=data) |
| 38 | ``` |
| 39 | --> |
| 40 | |
| 41 | === "Python" |
| 42 | |
| 43 | ```python |
| 44 | import lancedb |
| 45 | import numpy as np |
| 46 | |
| 47 | db = lancedb.connect("data/sample-lancedb") |
| 48 | |
| 49 | tbl = db.open_table("my_vectors") |
| 50 | |
| 51 | df = tbl.search(np.random.random((1536))) \ |
| 52 | .limit(10) \ |
| 53 | .to_list() |
| 54 | ``` |
| 55 | |
| 56 | === "TypeScript" |
| 57 | |
| 58 | === "@lancedb/lancedb" |
| 59 | |
| 60 | ```ts |
| 61 | --8<-- "nodejs/examples/search.ts:import" |
| 62 | |
| 63 | --8<-- "nodejs/examples/search.ts:search1" |
| 64 | ``` |
| 65 | |
| 66 | |
| 67 | === "vectordb (deprecated)" |
| 68 | |
| 69 | ```ts |
| 70 | --8<-- "docs/src/search_legacy.ts:import" |
| 71 | |
| 72 | --8<-- "docs/src/search_legacy.ts:search1" |
| 73 | ``` |
| 74 | |
| 75 | By default, `l2` will be used as metric type. You can specify the metric type as |
| 76 | `cosine` or `dot` if required. |
| 77 | |
| 78 | === "Python" |
| 79 | |
| 80 | ```python |
| 81 | df = tbl.search(np.random.random((1536))) \ |
| 82 | .metric("cosine") \ |
| 83 | .limit(10) \ |
| 84 | .to_list() |
| 85 | ``` |
| 86 | |
| 87 | === "TypeScript" |
| 88 | |
| 89 | === "@lancedb/lancedb" |
| 90 | |
| 91 | ```ts |
| 92 | --8<-- "nodejs/examples/search.ts:search2" |
| 93 | ``` |
| 94 | |
| 95 | === "vectordb (deprecated)" |
| 96 | |
| 97 | ```javascript |
| 98 | --8<-- "docs/src/search_legacy.ts:search2" |
| 99 | ``` |
| 100 | |
| 101 | ## Approximate nearest neighbor (ANN) search |
| 102 | |
| 103 | To perform scalable vector retrieval with acceptable latencies, it's common to build a vector index. |
| 104 | While the exhaustive search is guaranteed to always return 100% recall, the approximate nature of |
| 105 | an ANN search means that using an index often involves a trade-off between recall and latency. |
| 106 | |
| 107 | See the [IVF_PQ index](./concepts/index_ivfpq.md) for a deeper description of how `IVF_PQ` |
| 108 | indexes work in LanceDB. |
| 109 | |
| 110 | ## Output search results |
| 111 | |
| 112 | LanceDB returns vector search results via different formats commonly used in python. |
| 113 | Let's create a LanceDB table with a nested schema: |
| 114 | |
| 115 | === "Python" |
| 116 | |
| 117 | ```python |
| 118 | |
| 119 | from datetime import datetime |
| 120 | import lancedb |
| 121 | from lancedb.pydantic import LanceModel, Vector |
| 122 | import numpy as np |
| 123 | from pydantic import BaseModel |
| 124 | uri = "data/sample-lancedb-nested" |
| 125 | |
| 126 | class Metadata(BaseModel): |
| 127 | source: str |
| 128 | timestamp: datetime |
| 129 | |
| 130 | class Document(BaseModel): |
| 131 | content: str |
| 132 | meta: Metadata |
| 133 | |
| 134 | class LanceSchema(LanceModel): |
| 135 | id: str |
| 136 | vector: Vector(1536) |
| 137 | payload: Document |
| 138 | |
| 139 | # Let's add 100 sample rows to our dataset |
| 140 | data = [LanceSchema( |
| 141 | id=f"id{i}", |
| 142 | vector=np.random.randn(1536), |
| 143 | payload=Document( |
| 144 | content=f"document{i}", meta=Metadata(source=f"source{i % 10}", timestamp=datetime.now()) |
| 145 | ), |
| 146 | ) for i in range(100)] |
| 147 | |
| 148 | tbl = db.create_table("documents", data=data) |
| 149 | ``` |
| 150 | |
| 151 | ### As a PyArrow table |
| 152 | |
| 153 | Using `to_arrow()` we can get the results back as a pyarrow Table. |
| 154 | This result table has the same columns as the LanceDB table, with |
| 155 | the addition of an `_distance` column for vector search or a `score` |
| 156 | column for full text search. |
| 157 | |
| 158 | ```python |
| 159 | tbl.search(np.random.randn(1536)).to_arrow() |
| 160 | ``` |
| 161 | |
| 162 | ### As a Pandas DataFrame |
| 163 | |
| 164 | You can also get the results as a pandas dataframe. |
| 165 | |
| 166 | ```python |
| 167 | tbl.search(np.random.randn(1536)).to_pandas() |
| 168 | ``` |
| 169 | |
| 170 | While other formats like Arrow/Pydantic/Python dicts have a natural |
| 171 | way to handle nested schemas, pandas can only store nested data as a |
| 172 | python dict column, which makes it difficult to support nested references. |
| 173 | So for convenience, you can also tell LanceDB to flatten a nested schema |
| 174 | when creating the pandas dataframe. |
| 175 | |
| 176 | ```python |
| 177 | tbl.search(np.random.randn(1536)).to_pandas(flatten=True) |
| 178 | ``` |
| 179 | |
| 180 | If your table has a deeply nested struct, you can control how many levels |
| 181 | of nesting to flatten by passing in a positive integer. |
| 182 | |
| 183 | ```python |
| 184 | tbl.search(np.random.randn(1536)).to_pandas(flatten=1) |
| 185 | ``` |
| 186 | |
| 187 | ### As a list of Python dicts |
| 188 | |
| 189 | You can of course return results as a list of python dicts. |
| 190 | |
| 191 | ```python |
| 192 | tbl.search(np.random.randn(1536)).to_list() |
| 193 | ``` |
| 194 | |
| 195 | ### As a list of Pydantic models |
| 196 | |
| 197 | We can add data using Pydantic models, and we can certainly |
| 198 | retrieve results as Pydantic models |
| 199 | |
| 200 | ```python |
| 201 | tbl.search(np.random.randn(1536)).to_pydantic(LanceSchema) |
| 202 | ``` |
| 203 | |
| 204 | Note that in this case the extra `_distance` field is discarded since |
| 205 | it's not part of the LanceSchema. |