| 1 | // Copyright 2023 LanceDB 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 { Vector, tableFromIPC } from 'apache-arrow' |
| 16 | import { type EmbeddingFunction } from './embedding/embedding_function' |
| 17 | import { type MetricType } from '.' |
| 18 | |
| 19 | // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 20 | const { tableSearch } = require('../native.js') |
| 21 | |
| 22 | /** |
| 23 | * A builder for nearest neighbor queries for LanceDB. |
| 24 | */ |
| 25 | export class Query<T = number[]> { |
| 26 | private readonly _query?: T |
| 27 | private readonly _tbl?: any |
| 28 | private _queryVector?: number[] |
| 29 | private _limit?: number |
| 30 | private _refineFactor?: number |
| 31 | private _nprobes: number |
| 32 | private _select?: string[] |
| 33 | private _filter?: string |
| 34 | private _metricType?: MetricType |
| 35 | private _prefilter: boolean |
| 36 | private _fastSearch: boolean |
| 37 | protected readonly _embeddings?: EmbeddingFunction<T> |
| 38 | |
| 39 | constructor (query?: T, tbl?: any, embeddings?: EmbeddingFunction<T>) { |
| 40 | this._tbl = tbl |
| 41 | this._query = query |
| 42 | this._limit = 10 |
| 43 | this._nprobes = 20 |
| 44 | this._refineFactor = undefined |
| 45 | this._select = undefined |
| 46 | this._filter = undefined |
| 47 | this._metricType = undefined |
| 48 | this._embeddings = embeddings |
| 49 | this._prefilter = false |
| 50 | this._fastSearch = false |
| 51 | } |
| 52 | |
| 53 | /*** |
| 54 | * Sets the number of results that will be returned |
| 55 | * default value is 10 |
| 56 | * @param value number of results |
| 57 | */ |
| 58 | limit (value: number): Query<T> { |
| 59 | this._limit = value |
| 60 | return this |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Refine the results by reading extra elements and re-ranking them in memory. |
| 65 | * @param value refine factor to use in this query. |
| 66 | */ |
| 67 | refineFactor (value: number): Query<T> { |
| 68 | this._refineFactor = value |
| 69 | return this |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * The number of probes used. A higher number makes search more accurate but also slower. |
| 74 | * @param value The number of probes used. |
| 75 | */ |
| 76 | nprobes (value: number): Query<T> { |
| 77 | this._nprobes = value |
| 78 | return this |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * A filter statement to be applied to this query. |
| 83 | * @param value A filter in the same format used by a sql WHERE clause. |
| 84 | */ |
| 85 | filter (value: string): Query<T> { |
| 86 | this._filter = value |
| 87 | return this |
| 88 | } |
| 89 | |
| 90 | where = this.filter |
| 91 | |
| 92 | /** Return only the specified columns. |
| 93 | * |
| 94 | * @param value Only select the specified columns. If not specified, all columns will be returned. |
| 95 | */ |
| 96 | select (value: string[]): Query<T> { |
| 97 | this._select = value |
| 98 | return this |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * The MetricType used for this Query. |
| 103 | * @param value The metric to the. @see MetricType for the different options |
| 104 | */ |
| 105 | metricType (value: MetricType): Query<T> { |
| 106 | this._metricType = value |
| 107 | return this |
| 108 | } |
| 109 | |
| 110 | prefilter (value: boolean): Query<T> { |
| 111 | this._prefilter = value |
| 112 | return this |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * Skip searching un-indexed data. This can make search faster, but will miss |
| 117 | * any data that is not yet indexed. |
| 118 | */ |
| 119 | fastSearch (value: boolean): Query<T> { |
| 120 | this._fastSearch = value |
| 121 | return this |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Execute the query and return the results as an Array of Objects |
| 126 | */ |
| 127 | async execute<T = Record<string, unknown>> (): Promise<T[]> { |
| 128 | if (this._query !== undefined) { |
| 129 | if (this._embeddings !== undefined) { |
| 130 | this._queryVector = (await this._embeddings.embed([this._query]))[0] |
| 131 | } else { |
| 132 | this._queryVector = this._query as number[] |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | const isElectron = this.isElectron() |
| 137 | const buffer = await tableSearch.call(this._tbl, this, isElectron) |
| 138 | const data = tableFromIPC(buffer) |
| 139 | |
| 140 | return data.toArray().map((entry: Record<string, unknown>) => { |
| 141 | const newObject: Record<string, unknown> = {} |
| 142 | Object.keys(entry).forEach((key: string) => { |
| 143 | if (entry[key] instanceof Vector) { |
| 144 | // toJSON() returns f16 array correctly |
| 145 | newObject[key] = (entry[key] as any).toJSON() |
| 146 | } else { |
| 147 | newObject[key] = entry[key] as any |
| 148 | } |
| 149 | }) |
| 150 | return newObject as unknown as T |
| 151 | }) |
| 152 | } |
| 153 | |
| 154 | // See https://github.com/electron/electron/issues/2288 |
| 155 | private isElectron (): boolean { |
| 156 | try { |
| 157 | // eslint-disable-next-line no-prototype-builtins |
| 158 | return (process?.versions?.hasOwnProperty('electron') || navigator?.userAgent?.toLowerCase()?.includes(' electron')) |
| 159 | } catch (e) { |
| 160 | return false |
| 161 | } |
| 162 | } |
| 163 | } |