Elffuss BraidHub

kikocis/lancedb public

bbc8a2ecbe2c · 16.7 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 {
16 type EmbeddingFunction,
17 type Table,
18 type VectorIndexParams,
19 type Connection,
20 type ConnectionOptions,
21 type CreateTableOptions,
22 type VectorIndex,
23 type WriteOptions,
24 type IndexStats,
25 type UpdateArgs,
26 type UpdateSqlArgs,
27 makeArrowTable,
28 type MergeInsertArgs,
29 type ColumnAlteration
30} from '../index'
31import { Query } from '../query'
32
33import { Vector, Table as ArrowTable } from 'apache-arrow'
34import { HttpLancedbClient } from './client'
35import { isEmbeddingFunction } from '../embedding/embedding_function'
36import {
37 createEmptyTable,
38 fromRecordsToStreamBuffer,
39 fromTableToStreamBuffer
40} from '../arrow'
41import { toSQL, TTLCache } from '../util'
42import { type HttpMiddleware } from '../middleware'
43
44/**
45 * Remote connection.
46 */
47export class RemoteConnection implements Connection {
48 private _client: HttpLancedbClient
49 private readonly _dbName: string
50 private readonly _tableCache = new TTLCache(300_000)
51
52 constructor (opts: ConnectionOptions) {
53 if (!opts.uri.startsWith('db://')) {
54 throw new Error(`Invalid remote DB URI: ${opts.uri}`)
55 }
56 if (opts.apiKey == null || opts.apiKey === '') {
57 opts = Object.assign({}, opts, { apiKey: process.env.LANCEDB_API_KEY })
58 }
59 if (opts.apiKey === undefined || opts.region === undefined) {
60 throw new Error(
61 'API key and region are must be passed for remote connections. ' +
62 'API key can also be set through LANCEDB_API_KEY env variable.')
63 }
64
65 this._dbName = opts.uri.slice('db://'.length)
66 let server: string
67 if (opts.hostOverride === undefined) {
68 server = `https://${this._dbName}.${opts.region}.api.lancedb.com`
69 } else {
70 server = opts.hostOverride
71 }
72 this._client = new HttpLancedbClient(
73 server,
74 opts.apiKey,
75 opts.timeout,
76 opts.hostOverride === undefined ? undefined : this._dbName
77 )
78 }
79
80 get uri (): string {
81 // add the lancedb+ prefix back
82 return 'db://' + this._client.uri
83 }
84
85 async tableNames (
86 pageToken: string = '',
87 limit: number = 10
88 ): Promise<string[]> {
89 const response = await this._client.get('/v1/table/', {
90 limit: `${limit}`,
91 page_token: pageToken
92 })
93 const body = await response.body()
94 for (const table of body.tables) {
95 this._tableCache.set(table, true)
96 }
97 return body.tables
98 }
99
100 async openTable (name: string): Promise<Table>
101 async openTable<T>(
102 name: string,
103 embeddings: EmbeddingFunction<T>
104 ): Promise<Table<T>>
105 async openTable<T>(
106 name: string,
107 embeddings?: EmbeddingFunction<T>
108 ): Promise<Table<T>> {
109 // check if the table exists
110 if (this._tableCache.get(name) === undefined) {
111 await this._client.post(`/v1/table/${encodeURIComponent(name)}/describe/`)
112 this._tableCache.set(name, true)
113 }
114
115 if (embeddings !== undefined) {
116 return new RemoteTable(this._client, name, embeddings)
117 } else {
118 return new RemoteTable(this._client, name)
119 }
120 }
121
122 async createTable<T>(
123 nameOrOpts: string | CreateTableOptions<T>,
124 data?: Array<Record<string, unknown>> | ArrowTable,
125 optsOrEmbedding?: WriteOptions | EmbeddingFunction<T>,
126 opt?: WriteOptions
127 ): Promise<Table<T>> {
128 // Logic copied from LocatlConnection, refactor these to a base class + connectionImpl pattern
129 let schema
130 let embeddings: undefined | EmbeddingFunction<T>
131 let tableName: string
132 if (typeof nameOrOpts === 'string') {
133 if (
134 optsOrEmbedding !== undefined &&
135 isEmbeddingFunction(optsOrEmbedding)
136 ) {
137 embeddings = optsOrEmbedding
138 }
139 tableName = nameOrOpts
140 } else {
141 schema = nameOrOpts.schema
142 embeddings = nameOrOpts.embeddingFunction
143 tableName = nameOrOpts.name
144 if (data === undefined) {
145 data = nameOrOpts.data
146 }
147 }
148
149 let buffer: Buffer
150
151 function isEmpty (
152 data: Array<Record<string, unknown>> | ArrowTable<any>
153 ): boolean {
154 if (data instanceof ArrowTable) {
155 return data.numRows === 0
156 }
157 return data.length === 0
158 }
159
160 if (data === undefined || isEmpty(data)) {
161 if (schema === undefined) {
162 throw new Error('Either data or schema needs to defined')
163 }
164 buffer = await fromTableToStreamBuffer(createEmptyTable(schema))
165 } else if (data instanceof ArrowTable) {
166 buffer = await fromTableToStreamBuffer(data, embeddings)
167 } else {
168 // data is Array<Record<...>>
169 buffer = await fromRecordsToStreamBuffer(data, embeddings)
170 }
171
172 const res = await this._client.post(
173 `/v1/table/${encodeURIComponent(tableName)}/create/`,
174 buffer,
175 undefined,
176 'application/vnd.apache.arrow.stream'
177 )
178 if (res.status !== 200) {
179 throw new Error(
180 `Server Error, status: ${res.status}, ` +
181 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
182 `message: ${res.statusText}: ${await res.body()}`
183 )
184 }
185
186 this._tableCache.set(tableName, true)
187 if (embeddings === undefined) {
188 return new RemoteTable(this._client, tableName)
189 } else {
190 return new RemoteTable(this._client, tableName, embeddings)
191 }
192 }
193
194 async dropTable (name: string): Promise<void> {
195 await this._client.post(`/v1/table/${encodeURIComponent(name)}/drop/`)
196 this._tableCache.delete(name)
197 }
198
199 withMiddleware (middleware: HttpMiddleware): Connection {
200 const wrapped = this.clone()
201 wrapped._client = wrapped._client.withMiddleware(middleware)
202 return wrapped
203 }
204
205 private clone (): RemoteConnection {
206 const clone: RemoteConnection = Object.create(RemoteConnection.prototype)
207 return Object.assign(clone, this)
208 }
209}
210
211export class RemoteQuery<T = number[]> extends Query<T> {
212 constructor (
213 query: T,
214 private readonly _client: HttpLancedbClient,
215 private readonly _name: string,
216 embeddings?: EmbeddingFunction<T>
217 ) {
218 super(query, undefined, embeddings)
219 }
220
221 // TODO: refactor this to a base class + queryImpl pattern
222 async execute<T = Record<string, unknown>>(): Promise<T[]> {
223 const embeddings = this._embeddings
224 const query = (this as any)._query
225 let queryVector: number[]
226
227 if (embeddings !== undefined) {
228 queryVector = (await embeddings.embed([query]))[0]
229 } else {
230 queryVector = query as number[]
231 }
232
233 const data = await this._client.search(
234 this._name,
235 queryVector,
236 (this as any)._limit,
237 (this as any)._nprobes,
238 (this as any)._prefilter,
239 (this as any)._refineFactor,
240 (this as any)._select,
241 (this as any)._filter
242 )
243
244 return data.toArray().map((entry: Record<string, unknown>) => {
245 const newObject: Record<string, unknown> = {}
246 Object.keys(entry).forEach((key: string) => {
247 if (entry[key] instanceof Vector) {
248 newObject[key] = (entry[key] as Vector).toArray()
249 } else {
250 newObject[key] = entry[key]
251 }
252 })
253 return newObject as unknown as T
254 })
255 }
256}
257
258// we are using extend until we have next next version release
259// Table and Connection has both been refactored to interfaces
260export class RemoteTable<T = number[]> implements Table<T> {
261 private _client: HttpLancedbClient
262 private readonly _embeddings?: EmbeddingFunction<T>
263 private readonly _name: string
264
265 constructor (client: HttpLancedbClient, name: string)
266 constructor (
267 client: HttpLancedbClient,
268 name: string,
269 embeddings: EmbeddingFunction<T>
270 )
271 constructor (
272 client: HttpLancedbClient,
273 name: string,
274 embeddings?: EmbeddingFunction<T>
275 ) {
276 this._client = client
277 this._name = name
278 this._embeddings = embeddings
279 }
280
281 get name (): string {
282 return this._name
283 }
284
285 get schema (): Promise<any> {
286 return this._client
287 .post(`/v1/table/${encodeURIComponent(this._name)}/describe/`)
288 .then(async (res) => {
289 if (res.status !== 200) {
290 throw new Error(
291 `Server Error, status: ${res.status}, ` +
292 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
293 `message: ${res.statusText}: ${await res.body()}`
294 )
295 }
296 return (await res.body())?.schema
297 })
298 }
299
300 search (query: T): Query<T> {
301 return new RemoteQuery(query, this._client, encodeURIComponent(this._name)) //, this._embeddings_new)
302 }
303
304 filter (where: string): Query<T> {
305 throw new Error('Not implemented')
306 }
307
308 async mergeInsert (on: string, data: Array<Record<string, unknown>> | ArrowTable, args: MergeInsertArgs): Promise<void> {
309 let tbl: ArrowTable
310 if (data instanceof ArrowTable) {
311 tbl = data
312 } else {
313 tbl = makeArrowTable(data, await this.schema)
314 }
315
316 const queryParams: any = {
317 on
318 }
319 if (args.whenMatchedUpdateAll !== false && args.whenMatchedUpdateAll !== null && args.whenMatchedUpdateAll !== undefined) {
320 queryParams.when_matched_update_all = 'true'
321 if (typeof args.whenMatchedUpdateAll === 'string') {
322 queryParams.when_matched_update_all_filt = args.whenMatchedUpdateAll
323 }
324 } else {
325 queryParams.when_matched_update_all = 'false'
326 }
327 if (args.whenNotMatchedInsertAll ?? false) {
328 queryParams.when_not_matched_insert_all = 'true'
329 } else {
330 queryParams.when_not_matched_insert_all = 'false'
331 }
332 if (args.whenNotMatchedBySourceDelete !== false && args.whenNotMatchedBySourceDelete !== null && args.whenNotMatchedBySourceDelete !== undefined) {
333 queryParams.when_not_matched_by_source_delete = 'true'
334 if (typeof args.whenNotMatchedBySourceDelete === 'string') {
335 queryParams.when_not_matched_by_source_delete_filt = args.whenNotMatchedBySourceDelete
336 }
337 } else {
338 queryParams.when_not_matched_by_source_delete = 'false'
339 }
340
341 const buffer = await fromTableToStreamBuffer(tbl, this._embeddings)
342 const res = await this._client.post(
343 `/v1/table/${encodeURIComponent(this._name)}/merge_insert/`,
344 buffer,
345 queryParams,
346 'application/vnd.apache.arrow.stream'
347 )
348 if (res.status !== 200) {
349 throw new Error(
350 `Server Error, status: ${res.status}, ` +
351 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
352 `message: ${res.statusText}: ${await res.body()}`
353 )
354 }
355 }
356
357 async add (data: Array<Record<string, unknown>> | ArrowTable): Promise<number> {
358 let tbl: ArrowTable
359 if (data instanceof ArrowTable) {
360 tbl = data
361 } else {
362 tbl = makeArrowTable(data, await this.schema)
363 }
364
365 const buffer = await fromTableToStreamBuffer(tbl, this._embeddings)
366 const res = await this._client.post(
367 `/v1/table/${encodeURIComponent(this._name)}/insert/`,
368 buffer,
369 {
370 mode: 'append'
371 },
372 'application/vnd.apache.arrow.stream'
373 )
374 if (res.status !== 200) {
375 throw new Error(
376 `Server Error, status: ${res.status}, ` +
377 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
378 `message: ${res.statusText}: ${await res.body()}`
379 )
380 }
381 return tbl.numRows
382 }
383
384 async overwrite (data: Array<Record<string, unknown>> | ArrowTable): Promise<number> {
385 let tbl: ArrowTable
386 if (data instanceof ArrowTable) {
387 tbl = data
388 } else {
389 tbl = makeArrowTable(data)
390 }
391 const buffer = await fromTableToStreamBuffer(tbl, this._embeddings)
392 const res = await this._client.post(
393 `/v1/table/${encodeURIComponent(this._name)}/insert/`,
394 buffer,
395 {
396 mode: 'overwrite'
397 },
398 'application/vnd.apache.arrow.stream'
399 )
400 if (res.status !== 200) {
401 throw new Error(
402 `Server Error, status: ${res.status}, ` +
403 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
404 `message: ${res.statusText}: ${await res.body()}`
405 )
406 }
407 return tbl.numRows
408 }
409
410 async createIndex (indexParams: VectorIndexParams): Promise<void> {
411 const unsupportedParams = [
412 'index_name',
413 'num_partitions',
414 'max_iters',
415 'use_opq',
416 'num_sub_vectors',
417 'num_bits',
418 'max_opq_iters',
419 'replace'
420 ]
421 for (const param of unsupportedParams) {
422 // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
423 if (indexParams[param as keyof VectorIndexParams]) {
424 throw new Error(`${param} is not supported for remote connections`)
425 }
426 }
427
428 const column = indexParams.column ?? 'vector'
429 const indexType = 'vector'
430 const metricType = indexParams.metric_type ?? 'L2'
431 const indexCacheSize = indexParams.index_cache_size ?? null
432
433 const data = {
434 column,
435 index_type: indexType,
436 metric_type: metricType,
437 index_cache_size: indexCacheSize
438 }
439 const res = await this._client.post(
440 `/v1/table/${encodeURIComponent(this._name)}/create_index/`,
441 data
442 )
443 if (res.status !== 200) {
444 throw new Error(
445 `Server Error, status: ${res.status}, ` +
446 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
447 `message: ${res.statusText}: ${await res.body()}`
448 )
449 }
450 }
451
452 async createScalarIndex (column: string): Promise<void> {
453 const indexType = 'scalar'
454
455 const data = {
456 column,
457 index_type: indexType,
458 replace: true
459 }
460 const res = await this._client.post(
461 `/v1/table/${encodeURIComponent(this._name)}/create_scalar_index/`,
462 data
463 )
464 if (res.status !== 200) {
465 throw new Error(
466 `Server Error, status: ${res.status}, ` +
467 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
468 `message: ${res.statusText}: ${await res.body()}`
469 )
470 }
471 }
472
473 async countRows (filter?: string): Promise<number> {
474 const result = await this._client.post(`/v1/table/${encodeURIComponent(this._name)}/count_rows/`, {
475 predicate: filter
476 })
477 return (await result.body())
478 }
479
480 async delete (filter: string): Promise<void> {
481 await this._client.post(`/v1/table/${encodeURIComponent(this._name)}/delete/`, {
482 predicate: filter
483 })
484 }
485
486 async update (args: UpdateArgs | UpdateSqlArgs): Promise<void> {
487 let filter: string | null
488 let updates: Record<string, string>
489
490 if ('valuesSql' in args) {
491 filter = args.where ?? null
492 updates = args.valuesSql
493 } else {
494 filter = args.where ?? null
495 updates = {}
496 for (const [key, value] of Object.entries(args.values)) {
497 updates[key] = toSQL(value)
498 }
499 }
500 await this._client.post(`/v1/table/${encodeURIComponent(this._name)}/update/`, {
501 predicate: filter,
502 updates: Object.entries(updates).map(([key, value]) => [key, value])
503 })
504 }
505
506 async listIndices (): Promise<VectorIndex[]> {
507 const results = await this._client.post(
508 `/v1/table/${encodeURIComponent(this._name)}/index/list/`
509 )
510 return (await results.body()).indexes?.map((index: any) => ({
511 columns: index.columns,
512 name: index.index_name,
513 uuid: index.index_uuid,
514 status: index.status
515 }))
516 }
517
518 async indexStats (indexUuid: string): Promise<IndexStats> {
519 const results = await this._client.post(
520 `/v1/table/${encodeURIComponent(this._name)}/index/${indexUuid}/stats/`
521 )
522 const body = await results.body()
523 return {
524 numIndexedRows: body?.num_indexed_rows,
525 numUnindexedRows: body?.num_unindexed_rows,
526 indexType: body?.index_type,
527 distanceType: body?.distance_type,
528 completedAt: body?.completed_at
529 }
530 }
531
532 async addColumns (newColumnTransforms: Array<{ name: string, valueSql: string }>): Promise<void> {
533 throw new Error('Add columns is not yet supported in LanceDB Cloud.')
534 }
535
536 async alterColumns (columnAlterations: ColumnAlteration[]): Promise<void> {
537 throw new Error('Alter columns is not yet supported in LanceDB Cloud.')
538 }
539
540 async dropColumns (columnNames: string[]): Promise<void> {
541 throw new Error('Drop columns is not yet supported in LanceDB Cloud.')
542 }
543
544 withMiddleware(middleware: HttpMiddleware): Table<T> {
545 const wrapped = this.clone()
546 wrapped._client = wrapped._client.withMiddleware(middleware)
547 return wrapped
548 }
549
550 private clone (): RemoteTable<T> {
551 const clone: RemoteTable<T> = Object.create(RemoteTable.prototype)
552 return Object.assign(clone, this)
553 }
554}