| 1 | // Copyright 2024 Lance Developers. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | import { |
| 16 | Table as ArrowTable, |
| 17 | type IntoVector, |
| 18 | RecordBatch, |
| 19 | tableFromIPC, |
| 20 | } from "./arrow"; |
| 21 | import { type IvfPqOptions } from "./indices"; |
| 22 | import { |
| 23 | RecordBatchIterator as NativeBatchIterator, |
| 24 | Query as NativeQuery, |
| 25 | Table as NativeTable, |
| 26 | VectorQuery as NativeVectorQuery, |
| 27 | } from "./native"; |
| 28 | export class RecordBatchIterator implements AsyncIterator<RecordBatch> { |
| 29 | private promisedInner?: Promise<NativeBatchIterator>; |
| 30 | private inner?: NativeBatchIterator; |
| 31 | |
| 32 | constructor(promise?: Promise<NativeBatchIterator>) { |
| 33 | // TODO: check promise reliably so we dont need to pass two arguments. |
| 34 | this.promisedInner = promise; |
| 35 | } |
| 36 | |
| 37 | // biome-ignore lint/suspicious/noExplicitAny: skip |
| 38 | async next(): Promise<IteratorResult<RecordBatch<any>>> { |
| 39 | if (this.inner === undefined) { |
| 40 | this.inner = await this.promisedInner; |
| 41 | } |
| 42 | if (this.inner === undefined) { |
| 43 | throw new Error("Invalid iterator state state"); |
| 44 | } |
| 45 | const n = await this.inner.next(); |
| 46 | if (n == null) { |
| 47 | return Promise.resolve({ done: true, value: null }); |
| 48 | } |
| 49 | const tbl = tableFromIPC(n); |
| 50 | if (tbl.batches.length != 1) { |
| 51 | throw new Error("Expected only one batch"); |
| 52 | } |
| 53 | return Promise.resolve({ done: false, value: tbl.batches[0] }); |
| 54 | } |
| 55 | } |
| 56 | /* eslint-enable */ |
| 57 | |
| 58 | class RecordBatchIterable< |
| 59 | NativeQueryType extends NativeQuery | NativeVectorQuery, |
| 60 | > implements AsyncIterable<RecordBatch> |
| 61 | { |
| 62 | private inner: NativeQueryType; |
| 63 | private options?: QueryExecutionOptions; |
| 64 | |
| 65 | constructor(inner: NativeQueryType, options?: QueryExecutionOptions) { |
| 66 | this.inner = inner; |
| 67 | this.options = options; |
| 68 | } |
| 69 | |
| 70 | // biome-ignore lint/suspicious/noExplicitAny: skip |
| 71 | [Symbol.asyncIterator](): AsyncIterator<RecordBatch<any>, any, undefined> { |
| 72 | return new RecordBatchIterator( |
| 73 | this.inner.execute(this.options?.maxBatchLength), |
| 74 | ); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * Options that control the behavior of a particular query execution |
| 80 | */ |
| 81 | export interface QueryExecutionOptions { |
| 82 | /** |
| 83 | * The maximum number of rows to return in a single batch |
| 84 | * |
| 85 | * Batches may have fewer rows if the underlying data is stored |
| 86 | * in smaller chunks. |
| 87 | */ |
| 88 | maxBatchLength?: number; |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * Options that control the behavior of a full text search |
| 93 | */ |
| 94 | export interface FullTextSearchOptions { |
| 95 | /** |
| 96 | * The columns to search |
| 97 | * |
| 98 | * If not specified, all indexed columns will be searched. |
| 99 | * For now, only one column can be searched. |
| 100 | */ |
| 101 | columns?: string | string[]; |
| 102 | } |
| 103 | |
| 104 | /** Common methods supported by all query types */ |
| 105 | export class QueryBase<NativeQueryType extends NativeQuery | NativeVectorQuery> |
| 106 | implements AsyncIterable<RecordBatch> |
| 107 | { |
| 108 | protected constructor( |
| 109 | protected inner: NativeQueryType | Promise<NativeQueryType>, |
| 110 | ) { |
| 111 | // intentionally empty |
| 112 | } |
| 113 | |
| 114 | // call a function on the inner (either a promise or the actual object) |
| 115 | protected doCall(fn: (inner: NativeQueryType) => void) { |
| 116 | if (this.inner instanceof Promise) { |
| 117 | this.inner = this.inner.then((inner) => { |
| 118 | fn(inner); |
| 119 | return inner; |
| 120 | }); |
| 121 | } else { |
| 122 | fn(this.inner); |
| 123 | } |
| 124 | } |
| 125 | /** |
| 126 | * A filter statement to be applied to this query. |
| 127 | * |
| 128 | * The filter should be supplied as an SQL query string. For example: |
| 129 | * @example |
| 130 | * x > 10 |
| 131 | * y > 0 AND y < 100 |
| 132 | * x > 5 OR y = 'test' |
| 133 | * |
| 134 | * Filtering performance can often be improved by creating a scalar index |
| 135 | * on the filter column(s). |
| 136 | */ |
| 137 | where(predicate: string): this { |
| 138 | this.doCall((inner: NativeQueryType) => inner.onlyIf(predicate)); |
| 139 | return this; |
| 140 | } |
| 141 | /** |
| 142 | * A filter statement to be applied to this query. |
| 143 | * @alias where |
| 144 | * @deprecated Use `where` instead |
| 145 | */ |
| 146 | filter(predicate: string): this { |
| 147 | return this.where(predicate); |
| 148 | } |
| 149 | |
| 150 | fullTextSearch( |
| 151 | query: string, |
| 152 | options?: Partial<FullTextSearchOptions>, |
| 153 | ): this { |
| 154 | let columns: string[] | null = null; |
| 155 | if (options) { |
| 156 | if (typeof options.columns === "string") { |
| 157 | columns = [options.columns]; |
| 158 | } else if (Array.isArray(options.columns)) { |
| 159 | columns = options.columns; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | this.doCall((inner: NativeQueryType) => |
| 164 | inner.fullTextSearch(query, columns), |
| 165 | ); |
| 166 | return this; |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Return only the specified columns. |
| 171 | * |
| 172 | * By default a query will return all columns from the table. However, this can have |
| 173 | * a very significant impact on latency. LanceDb stores data in a columnar fashion. This |
| 174 | * means we can finely tune our I/O to select exactly the columns we need. |
| 175 | * |
| 176 | * As a best practice you should always limit queries to the columns that you need. If you |
| 177 | * pass in an array of column names then only those columns will be returned. |
| 178 | * |
| 179 | * You can also use this method to create new "dynamic" columns based on your existing columns. |
| 180 | * For example, you may not care about "a" or "b" but instead simply want "a + b". This is often |
| 181 | * seen in the SELECT clause of an SQL query (e.g. `SELECT a+b FROM my_table`). |
| 182 | * |
| 183 | * To create dynamic columns you can pass in a Map<string, string>. A column will be returned |
| 184 | * for each entry in the map. The key provides the name of the column. The value is |
| 185 | * an SQL string used to specify how the column is calculated. |
| 186 | * |
| 187 | * For example, an SQL query might state `SELECT a + b AS combined, c`. The equivalent |
| 188 | * input to this method would be: |
| 189 | * @example |
| 190 | * new Map([["combined", "a + b"], ["c", "c"]]) |
| 191 | * |
| 192 | * Columns will always be returned in the order given, even if that order is different than |
| 193 | * the order used when adding the data. |
| 194 | * |
| 195 | * Note that you can pass in a `Record<string, string>` (e.g. an object literal). This method |
| 196 | * uses `Object.entries` which should preserve the insertion order of the object. However, |
| 197 | * object insertion order is easy to get wrong and `Map` is more foolproof. |
| 198 | */ |
| 199 | select( |
| 200 | columns: string[] | Map<string, string> | Record<string, string> | string, |
| 201 | ): this { |
| 202 | const selectColumns = (columnArray: string[]) => { |
| 203 | this.doCall((inner: NativeQueryType) => { |
| 204 | inner.selectColumns(columnArray); |
| 205 | }); |
| 206 | }; |
| 207 | const selectMapping = (columnTuples: [string, string][]) => { |
| 208 | this.doCall((inner: NativeQueryType) => { |
| 209 | inner.select(columnTuples); |
| 210 | }); |
| 211 | }; |
| 212 | |
| 213 | if (typeof columns === "string") { |
| 214 | selectColumns([columns]); |
| 215 | } else if (Array.isArray(columns)) { |
| 216 | selectColumns(columns); |
| 217 | } else if (columns instanceof Map) { |
| 218 | selectMapping(Array.from(columns.entries())); |
| 219 | } else { |
| 220 | selectMapping(Object.entries(columns)); |
| 221 | } |
| 222 | |
| 223 | return this; |
| 224 | } |
| 225 | |
| 226 | /** |
| 227 | * Set the maximum number of results to return. |
| 228 | * |
| 229 | * By default, a plain search has no limit. If this method is not |
| 230 | * called then every valid row from the table will be returned. |
| 231 | */ |
| 232 | limit(limit: number): this { |
| 233 | this.doCall((inner: NativeQueryType) => inner.limit(limit)); |
| 234 | return this; |
| 235 | } |
| 236 | |
| 237 | offset(offset: number): this { |
| 238 | this.doCall((inner: NativeQueryType) => inner.offset(offset)); |
| 239 | return this; |
| 240 | } |
| 241 | |
| 242 | protected nativeExecute( |
| 243 | options?: Partial<QueryExecutionOptions>, |
| 244 | ): Promise<NativeBatchIterator> { |
| 245 | if (this.inner instanceof Promise) { |
| 246 | return this.inner.then((inner) => inner.execute(options?.maxBatchLength)); |
| 247 | } else { |
| 248 | return this.inner.execute(options?.maxBatchLength); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | /** |
| 253 | * Execute the query and return the results as an @see {@link AsyncIterator} |
| 254 | * of @see {@link RecordBatch}. |
| 255 | * |
| 256 | * By default, LanceDb will use many threads to calculate results and, when |
| 257 | * the result set is large, multiple batches will be processed at one time. |
| 258 | * This readahead is limited however and backpressure will be applied if this |
| 259 | * stream is consumed slowly (this constrains the maximum memory used by a |
| 260 | * single query) |
| 261 | * |
| 262 | */ |
| 263 | protected execute( |
| 264 | options?: Partial<QueryExecutionOptions>, |
| 265 | ): RecordBatchIterator { |
| 266 | return new RecordBatchIterator(this.nativeExecute(options)); |
| 267 | } |
| 268 | |
| 269 | // biome-ignore lint/suspicious/noExplicitAny: skip |
| 270 | [Symbol.asyncIterator](): AsyncIterator<RecordBatch<any>> { |
| 271 | const promise = this.nativeExecute(); |
| 272 | return new RecordBatchIterator(promise); |
| 273 | } |
| 274 | |
| 275 | /** Collect the results as an Arrow @see {@link ArrowTable}. */ |
| 276 | async toArrow(options?: Partial<QueryExecutionOptions>): Promise<ArrowTable> { |
| 277 | const batches = []; |
| 278 | let inner; |
| 279 | if (this.inner instanceof Promise) { |
| 280 | inner = await this.inner; |
| 281 | } else { |
| 282 | inner = this.inner; |
| 283 | } |
| 284 | for await (const batch of new RecordBatchIterable(inner, options)) { |
| 285 | batches.push(batch); |
| 286 | } |
| 287 | return new ArrowTable(batches); |
| 288 | } |
| 289 | |
| 290 | /** Collect the results as an array of objects. */ |
| 291 | // biome-ignore lint/suspicious/noExplicitAny: arrow.toArrow() returns any[] |
| 292 | async toArray(options?: Partial<QueryExecutionOptions>): Promise<any[]> { |
| 293 | const tbl = await this.toArrow(options); |
| 294 | return tbl.toArray(); |
| 295 | } |
| 296 | |
| 297 | /** |
| 298 | * Generates an explanation of the query execution plan. |
| 299 | * |
| 300 | * @example |
| 301 | * import * as lancedb from "@lancedb/lancedb" |
| 302 | * const db = await lancedb.connect("./.lancedb"); |
| 303 | * const table = await db.createTable("my_table", [ |
| 304 | * { vector: [1.1, 0.9], id: "1" }, |
| 305 | * ]); |
| 306 | * const plan = await table.query().nearestTo([0.5, 0.2]).explainPlan(); |
| 307 | * |
| 308 | * @param verbose - If true, provides a more detailed explanation. Defaults to false. |
| 309 | * @returns A Promise that resolves to a string containing the query execution plan explanation. |
| 310 | */ |
| 311 | async explainPlan(verbose = false): Promise<string> { |
| 312 | if (this.inner instanceof Promise) { |
| 313 | return this.inner.then((inner) => inner.explainPlan(verbose)); |
| 314 | } else { |
| 315 | return this.inner.explainPlan(verbose); |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | /** |
| 321 | * An interface for a query that can be executed |
| 322 | * |
| 323 | * Supported by all query types |
| 324 | */ |
| 325 | export interface ExecutableQuery {} |
| 326 | |
| 327 | /** |
| 328 | * A builder used to construct a vector search |
| 329 | * |
| 330 | * This builder can be reused to execute the query many times. |
| 331 | */ |
| 332 | export class VectorQuery extends QueryBase<NativeVectorQuery> { |
| 333 | constructor(inner: NativeVectorQuery | Promise<NativeVectorQuery>) { |
| 334 | super(inner); |
| 335 | } |
| 336 | |
| 337 | /** |
| 338 | * Set the number of partitions to search (probe) |
| 339 | * |
| 340 | * This argument is only used when the vector column has an IVF PQ index. |
| 341 | * If there is no index then this value is ignored. |
| 342 | * |
| 343 | * The IVF stage of IVF PQ divides the input into partitions (clusters) of |
| 344 | * related values. |
| 345 | * |
| 346 | * The partition whose centroids are closest to the query vector will be |
| 347 | * exhaustiely searched to find matches. This parameter controls how many |
| 348 | * partitions should be searched. |
| 349 | * |
| 350 | * Increasing this value will increase the recall of your query but will |
| 351 | * also increase the latency of your query. The default value is 20. This |
| 352 | * default is good for many cases but the best value to use will depend on |
| 353 | * your data and the recall that you need to achieve. |
| 354 | * |
| 355 | * For best results we recommend tuning this parameter with a benchmark against |
| 356 | * your actual data to find the smallest possible value that will still give |
| 357 | * you the desired recall. |
| 358 | */ |
| 359 | nprobes(nprobes: number): VectorQuery { |
| 360 | super.doCall((inner) => inner.nprobes(nprobes)); |
| 361 | |
| 362 | return this; |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Set the vector column to query |
| 367 | * |
| 368 | * This controls which column is compared to the query vector supplied in |
| 369 | * the call to @see {@link Query#nearestTo} |
| 370 | * |
| 371 | * This parameter must be specified if the table has more than one column |
| 372 | * whose data type is a fixed-size-list of floats. |
| 373 | */ |
| 374 | column(column: string): VectorQuery { |
| 375 | super.doCall((inner) => inner.column(column)); |
| 376 | return this; |
| 377 | } |
| 378 | |
| 379 | /** |
| 380 | * Set the distance metric to use |
| 381 | * |
| 382 | * When performing a vector search we try and find the "nearest" vectors according |
| 383 | * to some kind of distance metric. This parameter controls which distance metric to |
| 384 | * use. See @see {@link IvfPqOptions.distanceType} for more details on the different |
| 385 | * distance metrics available. |
| 386 | * |
| 387 | * Note: if there is a vector index then the distance type used MUST match the distance |
| 388 | * type used to train the vector index. If this is not done then the results will be |
| 389 | * invalid. |
| 390 | * |
| 391 | * By default "l2" is used. |
| 392 | */ |
| 393 | distanceType( |
| 394 | distanceType: Required<IvfPqOptions>["distanceType"], |
| 395 | ): VectorQuery { |
| 396 | super.doCall((inner) => inner.distanceType(distanceType)); |
| 397 | return this; |
| 398 | } |
| 399 | |
| 400 | /** |
| 401 | * A multiplier to control how many additional rows are taken during the refine step |
| 402 | * |
| 403 | * This argument is only used when the vector column has an IVF PQ index. |
| 404 | * If there is no index then this value is ignored. |
| 405 | * |
| 406 | * An IVF PQ index stores compressed (quantized) values. They query vector is compared |
| 407 | * against these values and, since they are compressed, the comparison is inaccurate. |
| 408 | * |
| 409 | * This parameter can be used to refine the results. It can improve both improve recall |
| 410 | * and correct the ordering of the nearest results. |
| 411 | * |
| 412 | * To refine results LanceDb will first perform an ANN search to find the nearest |
| 413 | * `limit` * `refine_factor` results. In other words, if `refine_factor` is 3 and |
| 414 | * `limit` is the default (10) then the first 30 results will be selected. LanceDb |
| 415 | * then fetches the full, uncompressed, values for these 30 results. The results are |
| 416 | * then reordered by the true distance and only the nearest 10 are kept. |
| 417 | * |
| 418 | * Note: there is a difference between calling this method with a value of 1 and never |
| 419 | * calling this method at all. Calling this method with any value will have an impact |
| 420 | * on your search latency. When you call this method with a `refine_factor` of 1 then |
| 421 | * LanceDb still needs to fetch the full, uncompressed, values so that it can potentially |
| 422 | * reorder the results. |
| 423 | * |
| 424 | * Note: if this method is NOT called then the distances returned in the _distance column |
| 425 | * will be approximate distances based on the comparison of the quantized query vector |
| 426 | * and the quantized result vectors. This can be considerably different than the true |
| 427 | * distance between the query vector and the actual uncompressed vector. |
| 428 | */ |
| 429 | refineFactor(refineFactor: number): VectorQuery { |
| 430 | super.doCall((inner) => inner.refineFactor(refineFactor)); |
| 431 | return this; |
| 432 | } |
| 433 | |
| 434 | /** |
| 435 | * If this is called then filtering will happen after the vector search instead of |
| 436 | * before. |
| 437 | * |
| 438 | * By default filtering will be performed before the vector search. This is how |
| 439 | * filtering is typically understood to work. This prefilter step does add some |
| 440 | * additional latency. Creating a scalar index on the filter column(s) can |
| 441 | * often improve this latency. However, sometimes a filter is too complex or scalar |
| 442 | * indices cannot be applied to the column. In these cases postfiltering can be |
| 443 | * used instead of prefiltering to improve latency. |
| 444 | * |
| 445 | * Post filtering applies the filter to the results of the vector search. This means |
| 446 | * we only run the filter on a much smaller set of data. However, it can cause the |
| 447 | * query to return fewer than `limit` results (or even no results) if none of the nearest |
| 448 | * results match the filter. |
| 449 | * |
| 450 | * Post filtering happens during the "refine stage" (described in more detail in |
| 451 | * @see {@link VectorQuery#refineFactor}). This means that setting a higher refine |
| 452 | * factor can often help restore some of the results lost by post filtering. |
| 453 | */ |
| 454 | postfilter(): VectorQuery { |
| 455 | super.doCall((inner) => inner.postfilter()); |
| 456 | return this; |
| 457 | } |
| 458 | |
| 459 | /** |
| 460 | * If this is called then any vector index is skipped |
| 461 | * |
| 462 | * An exhaustive (flat) search will be performed. The query vector will |
| 463 | * be compared to every vector in the table. At high scales this can be |
| 464 | * expensive. However, this is often still useful. For example, skipping |
| 465 | * the vector index can give you ground truth results which you can use to |
| 466 | * calculate your recall to select an appropriate value for nprobes. |
| 467 | */ |
| 468 | bypassVectorIndex(): VectorQuery { |
| 469 | super.doCall((inner) => inner.bypassVectorIndex()); |
| 470 | return this; |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | /** A builder for LanceDB queries. */ |
| 475 | export class Query extends QueryBase<NativeQuery> { |
| 476 | constructor(tbl: NativeTable) { |
| 477 | super(tbl.query()); |
| 478 | } |
| 479 | |
| 480 | /** |
| 481 | * Find the nearest vectors to the given query vector. |
| 482 | * |
| 483 | * This converts the query from a plain query to a vector query. |
| 484 | * |
| 485 | * This method will attempt to convert the input to the query vector |
| 486 | * expected by the embedding model. If the input cannot be converted |
| 487 | * then an error will be thrown. |
| 488 | * |
| 489 | * By default, there is no embedding model, and the input should be |
| 490 | * an array-like object of numbers (something that can be used as input |
| 491 | * to Float32Array.from) |
| 492 | * |
| 493 | * If there is only one vector column (a column whose data type is a |
| 494 | * fixed size list of floats) then the column does not need to be specified. |
| 495 | * If there is more than one vector column you must use |
| 496 | * @see {@link VectorQuery#column} to specify which column you would like |
| 497 | * to compare with. |
| 498 | * |
| 499 | * If no index has been created on the vector column then a vector query |
| 500 | * will perform a distance comparison between the query vector and every |
| 501 | * vector in the database and then sort the results. This is sometimes |
| 502 | * called a "flat search" |
| 503 | * |
| 504 | * For small databases, with a few hundred thousand vectors or less, this can |
| 505 | * be reasonably fast. In larger databases you should create a vector index |
| 506 | * on the column. If there is a vector index then an "approximate" nearest |
| 507 | * neighbor search (frequently called an ANN search) will be performed. This |
| 508 | * search is much faster, but the results will be approximate. |
| 509 | * |
| 510 | * The query can be further parameterized using the returned builder. There |
| 511 | * are various ANN search parameters that will let you fine tune your recall |
| 512 | * accuracy vs search latency. |
| 513 | * |
| 514 | * Vector searches always have a `limit`. If `limit` has not been called then |
| 515 | * a default `limit` of 10 will be used. @see {@link Query#limit} |
| 516 | */ |
| 517 | nearestTo(vector: IntoVector): VectorQuery { |
| 518 | if (this.inner instanceof Promise) { |
| 519 | const nativeQuery = this.inner.then(async (inner) => { |
| 520 | if (vector instanceof Promise) { |
| 521 | const arr = await vector.then((v) => Float32Array.from(v)); |
| 522 | return inner.nearestTo(arr); |
| 523 | } else { |
| 524 | return inner.nearestTo(Float32Array.from(vector)); |
| 525 | } |
| 526 | }); |
| 527 | return new VectorQuery(nativeQuery); |
| 528 | } |
| 529 | if (vector instanceof Promise) { |
| 530 | const res = (async () => { |
| 531 | try { |
| 532 | const v = await vector; |
| 533 | const arr = Float32Array.from(v); |
| 534 | // |
| 535 | // biome-ignore lint/suspicious/noExplicitAny: we need to get the `inner`, but js has no package scoping |
| 536 | const value: any = this.nearestTo(arr); |
| 537 | const inner = value.inner as |
| 538 | | NativeVectorQuery |
| 539 | | Promise<NativeVectorQuery>; |
| 540 | return inner; |
| 541 | } catch (e) { |
| 542 | return Promise.reject(e); |
| 543 | } |
| 544 | })(); |
| 545 | return new VectorQuery(res); |
| 546 | } else { |
| 547 | const vectorQuery = this.inner.nearestTo(Float32Array.from(vector)); |
| 548 | return new VectorQuery(vectorQuery); |
| 549 | } |
| 550 | } |
| 551 | } |