Elffuss BraidHub

kikocis/lancedb public

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