Elffuss BraidHub

kikocis/lancedb public

main · 39.7 KiBRawPermalink
1// Copyright 2023 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
15import { type Schema, Table as ArrowTable, tableFromIPC } from "apache-arrow";
16import {
17 createEmptyTable,
18 fromRecordsToBuffer,
19 fromTableToBuffer,
20 makeArrowTable
21} from "./arrow";
22import type { EmbeddingFunction } from "./embedding/embedding_function";
23import { RemoteConnection } from "./remote";
24import { Query } from "./query";
25import { isEmbeddingFunction } from "./embedding/embedding_function";
26import { type Literal, toSQL } from "./util";
27
28import { type HttpMiddleware } from "./middleware";
29
30const {
31 databaseNew,
32 databaseTableNames,
33 databaseOpenTable,
34 databaseDropTable,
35 tableCreate,
36 tableAdd,
37 tableCreateScalarIndex,
38 tableCreateVectorIndex,
39 tableCountRows,
40 tableDelete,
41 tableUpdate,
42 tableMergeInsert,
43 tableCleanupOldVersions,
44 tableCompactFiles,
45 tableListIndices,
46 tableIndexStats,
47 tableSchema,
48 tableAddColumns,
49 tableAlterColumns,
50 tableDropColumns
51 // eslint-disable-next-line @typescript-eslint/no-var-requires
52} = require("../native.js");
53
54export { Query };
55export type { EmbeddingFunction };
56export { OpenAIEmbeddingFunction } from "./embedding/openai";
57export {
58 convertToTable,
59 makeArrowTable,
60 type MakeArrowTableOptions
61} from "./arrow";
62
63const defaultAwsRegion = "us-east-1";
64
65const defaultRequestTimeout = 10_000
66
67export interface AwsCredentials {
68 accessKeyId: string
69
70 secretKey: string
71
72 sessionToken?: string
73}
74
75export interface ConnectionOptions {
76 /**
77 * LanceDB database URI.
78 *
79 * - `/path/to/database` - local database
80 * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
81 * - `db://host:port` - remote database (LanceDB cloud)
82 */
83 uri: string
84
85 /** User provided AWS crednetials.
86 *
87 * If not provided, LanceDB will use the default credentials provider chain.
88 *
89 * @deprecated Pass `aws_access_key_id`, `aws_secret_access_key`, and `aws_session_token`
90 * through `storageOptions` instead.
91 */
92 awsCredentials?: AwsCredentials
93
94 /** AWS region to connect to. Default is {@link defaultAwsRegion}
95 *
96 * @deprecated Pass `region` through `storageOptions` instead.
97 */
98 awsRegion?: string
99
100 /**
101 * User provided options for object storage. For example, S3 credentials or request timeouts.
102 *
103 * The various options are described at https://lancedb.github.io/lancedb/guides/storage/
104 */
105 storageOptions?: Record<string, string>
106
107 /**
108 * API key for the remote connections
109 *
110 * Can also be passed by setting environment variable `LANCEDB_API_KEY`
111 */
112 apiKey?: string
113
114 /** Region to connect. Default is 'us-east-1' */
115 region?: string
116
117 /**
118 * Override the host URL for the remote connection.
119 *
120 * This is useful for local testing.
121 */
122 hostOverride?: string
123
124 /**
125 * Duration in milliseconds for request timeout. Default = 10,000 (10 seconds)
126 */
127 timeout?: number
128
129 /**
130 * (For LanceDB OSS only): The interval, in seconds, at which to check for
131 * updates to the table from other processes. If None, then consistency is not
132 * checked. For performance reasons, this is the default. For strong
133 * consistency, set this to zero seconds. Then every read will check for
134 * updates from other processes. As a compromise, you can set this to a
135 * non-zero value for eventual consistency. If more than that interval
136 * has passed since the last check, then the table will be checked for updates.
137 * Note: this consistency only applies to read operations. Write operations are
138 * always consistent.
139 */
140 readConsistencyInterval?: number
141}
142
143function getAwsArgs(opts: ConnectionOptions): any[] {
144 const callArgs: any[] = [];
145 const awsCredentials = opts.awsCredentials;
146 if (awsCredentials !== undefined) {
147 callArgs.push(awsCredentials.accessKeyId);
148 callArgs.push(awsCredentials.secretKey);
149 callArgs.push(awsCredentials.sessionToken);
150 } else {
151 callArgs.fill(undefined, 0, 3);
152 }
153
154 callArgs.push(opts.awsRegion);
155 return callArgs;
156}
157
158export interface CreateTableOptions<T> {
159 // Name of Table
160 name: string
161
162 // Data to insert into the Table
163 data?: Array<Record<string, unknown>> | ArrowTable | undefined
164
165 // Optional Arrow Schema for this table
166 schema?: Schema | undefined
167
168 // Optional embedding function used to create embeddings
169 embeddingFunction?: EmbeddingFunction<T> | undefined
170
171 // WriteOptions for this operation
172 writeOptions?: WriteOptions | undefined
173}
174
175/**
176 * Connect to a LanceDB instance at the given URI.
177 *
178 * Accepted formats:
179 *
180 * - `/path/to/database` - local database
181 * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
182 * - `db://host:port` - remote database (LanceDB cloud)
183 *
184 * @param uri The uri of the database. If the database uri starts with `db://` then it connects to a remote database.
185 *
186 * @see {@link ConnectionOptions} for more details on the URI format.
187 */
188export async function connect(uri: string): Promise<Connection>;
189/**
190 * Connect to a LanceDB instance with connection options.
191 *
192 * @param opts The {@link ConnectionOptions} to use when connecting to the database.
193 */
194export async function connect(
195 opts: Partial<ConnectionOptions>
196): Promise<Connection>;
197export async function connect(
198 arg: string | Partial<ConnectionOptions>
199): Promise<Connection> {
200 let partOpts: Partial<ConnectionOptions>;
201 if (typeof arg === "string") {
202 partOpts = { uri: arg };
203 } else {
204 const keys = Object.keys(arg);
205 if (keys.length === 1 && keys[0] === "uri" && typeof arg.uri === "string") {
206 partOpts = { uri: arg.uri };
207 } else {
208 partOpts = arg;
209 }
210 }
211
212 let defaultRegion = process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION;
213 defaultRegion = (defaultRegion ?? "").trim() !== "" ? defaultRegion : defaultAwsRegion;
214
215 const opts: ConnectionOptions = {
216 uri: partOpts.uri ?? "",
217 awsCredentials: partOpts.awsCredentials ?? undefined,
218 awsRegion: partOpts.awsRegion ?? defaultRegion,
219 apiKey: partOpts.apiKey ?? undefined,
220 region: partOpts.region ?? defaultRegion,
221 timeout: partOpts.timeout ?? defaultRequestTimeout,
222 readConsistencyInterval: partOpts.readConsistencyInterval ?? undefined,
223 storageOptions: partOpts.storageOptions ?? undefined,
224 hostOverride: partOpts.hostOverride ?? undefined
225 }
226 if (opts.uri.startsWith("db://")) {
227 // Remote connection
228 return new RemoteConnection(opts);
229 }
230
231 const storageOptions = opts.storageOptions ?? {};
232 if (opts.awsCredentials?.accessKeyId !== undefined) {
233 storageOptions.aws_access_key_id = opts.awsCredentials.accessKeyId;
234 }
235 if (opts.awsCredentials?.secretKey !== undefined) {
236 storageOptions.aws_secret_access_key = opts.awsCredentials.secretKey;
237 }
238 if (opts.awsCredentials?.sessionToken !== undefined) {
239 storageOptions.aws_session_token = opts.awsCredentials.sessionToken;
240 }
241 if (opts.awsRegion !== undefined) {
242 storageOptions.region = opts.awsRegion;
243 }
244 // It's a pain to pass a record to Rust, so we convert it to an array of key-value pairs
245 const storageOptionsArr = Object.entries(storageOptions);
246
247 const db = await databaseNew(
248 opts.uri,
249 storageOptionsArr,
250 opts.readConsistencyInterval
251 );
252 return new LocalConnection(db, opts);
253}
254
255/**
256 * A LanceDB Connection that allows you to open tables and create new ones.
257 *
258 * Connection could be local against filesystem or remote against a server.
259 */
260export interface Connection {
261 uri: string
262
263 tableNames(): Promise<string[]>
264
265 /**
266 * Open a table in the database.
267 *
268 * @param name The name of the table.
269 * @param embeddings An embedding function to use on this table
270 */
271 openTable<T>(
272 name: string,
273 embeddings?: EmbeddingFunction<T>
274 ): Promise<Table<T>>
275
276 /**
277 * Creates a new Table, optionally initializing it with new data.
278 *
279 * @param {string} name - The name of the table.
280 * @param data - Array of Records to be inserted into the table
281 * @param schema - An Arrow Schema that describe this table columns
282 * @param {EmbeddingFunction} embeddings - An embedding function to use on this table
283 * @param {WriteOptions} writeOptions - The write options to use when creating the table.
284 */
285 createTable<T>({
286 name,
287 data,
288 schema,
289 embeddingFunction,
290 writeOptions
291 }: CreateTableOptions<T>): Promise<Table<T>>
292
293 /**
294 * Creates a new Table and initialize it with new data.
295 *
296 * @param {string} name - The name of the table.
297 * @param data - Non-empty Array of Records to be inserted into the table
298 */
299 createTable(
300 name: string,
301 data: Array<Record<string, unknown>> | ArrowTable
302 ): Promise<Table>
303
304 /**
305 * Creates a new Table and initialize it with new data.
306 *
307 * @param {string} name - The name of the table.
308 * @param data - Non-empty Array of Records to be inserted into the table
309 * @param {WriteOptions} options - The write options to use when creating the table.
310 */
311 createTable(
312 name: string,
313 data: Array<Record<string, unknown>> | ArrowTable,
314 options: WriteOptions
315 ): Promise<Table>
316
317 /**
318 * Creates a new Table and initialize it with new data.
319 *
320 * @param {string} name - The name of the table.
321 * @param data - Non-empty Array of Records to be inserted into the table
322 * @param {EmbeddingFunction} embeddings - An embedding function to use on this table
323 */
324 createTable<T>(
325 name: string,
326 data: Array<Record<string, unknown>> | ArrowTable,
327 embeddings: EmbeddingFunction<T>
328 ): Promise<Table<T>>
329 /**
330 * Creates a new Table and initialize it with new data.
331 *
332 * @param {string} name - The name of the table.
333 * @param data - Non-empty Array of Records to be inserted into the table
334 * @param {EmbeddingFunction} embeddings - An embedding function to use on this table
335 * @param {WriteOptions} options - The write options to use when creating the table.
336 */
337 createTable<T>(
338 name: string,
339 data: Array<Record<string, unknown>> | ArrowTable,
340 embeddings: EmbeddingFunction<T>,
341 options: WriteOptions
342 ): Promise<Table<T>>
343
344 /**
345 * Drop an existing table.
346 * @param name The name of the table to drop.
347 */
348 dropTable(name: string): Promise<void>
349
350 /**
351 * Instrument the behavior of this Connection with middleware.
352 *
353 * The middleware will be called in the order they are added.
354 *
355 * Currently this functionality is only supported for remote Connections.
356 *
357 * @param {HttpMiddleware} - Middleware which will instrument the Connection.
358 * @returns - this Connection instrumented by the passed middleware
359 */
360 withMiddleware(middleware: HttpMiddleware): Connection
361}
362
363/**
364 * A LanceDB Table is the collection of Records. Each Record has one or more vector fields.
365 */
366export interface Table<T = number[]> {
367 name: string
368
369 /**
370 * Creates a search query to find the nearest neighbors of the given search term
371 * @param query The query search term
372 */
373 search: (query: T) => Query<T>
374
375 /**
376 * Insert records into this Table.
377 *
378 * @param data Records to be inserted into the Table
379 * @return The number of rows added to the table
380 */
381 add: (data: Array<Record<string, unknown>> | ArrowTable) => Promise<number>
382
383 /**
384 * Insert records into this Table, replacing its contents.
385 *
386 * @param data Records to be inserted into the Table
387 * @return The number of rows added to the table
388 */
389 overwrite: (
390 data: Array<Record<string, unknown>> | ArrowTable
391 ) => Promise<number>
392
393 /**
394 * Create an ANN index on this Table vector index.
395 *
396 * @param indexParams The parameters of this Index, @see VectorIndexParams.
397 */
398 createIndex: (indexParams: VectorIndexParams) => Promise<any>
399
400 /**
401 * Create a scalar index on this Table for the given column
402 *
403 * @param column The column to index
404 * @param replace If false, fail if an index already exists on the column
405 * it is always set to true for remote connections
406 *
407 * Scalar indices, like vector indices, can be used to speed up scans. A scalar
408 * index can speed up scans that contain filter expressions on the indexed column.
409 * For example, the following scan will be faster if the column `my_col` has
410 * a scalar index:
411 *
412 * ```ts
413 * const con = await lancedb.connect('./.lancedb');
414 * const table = await con.openTable('images');
415 * const results = await table.where('my_col = 7').execute();
416 * ```
417 *
418 * Scalar indices can also speed up scans containing a vector search and a
419 * prefilter:
420 *
421 * ```ts
422 * const con = await lancedb.connect('././lancedb');
423 * const table = await con.openTable('images');
424 * const results = await table.search([1.0, 2.0]).where('my_col != 7').prefilter(true);
425 * ```
426 *
427 * Scalar indices can only speed up scans for basic filters using
428 * equality, comparison, range (e.g. `my_col BETWEEN 0 AND 100`), and set
429 * membership (e.g. `my_col IN (0, 1, 2)`)
430 *
431 * Scalar indices can be used if the filter contains multiple indexed columns and
432 * the filter criteria are AND'd or OR'd together
433 * (e.g. `my_col < 0 AND other_col> 100`)
434 *
435 * Scalar indices may be used if the filter contains non-indexed columns but,
436 * depending on the structure of the filter, they may not be usable. For example,
437 * if the column `not_indexed` does not have a scalar index then the filter
438 * `my_col = 0 OR not_indexed = 1` will not be able to use any scalar index on
439 * `my_col`.
440 *
441 * @examples
442 *
443 * ```ts
444 * const con = await lancedb.connect('././lancedb')
445 * const table = await con.openTable('images')
446 * await table.createScalarIndex('my_col')
447 * ```
448 */
449 createScalarIndex: (column: string, replace?: boolean) => Promise<void>
450
451 /**
452 * Returns the number of rows in this table.
453 */
454 countRows: (filter?: string) => Promise<number>
455
456 /**
457 * Delete rows from this table.
458 *
459 * This can be used to delete a single row, many rows, all rows, or
460 * sometimes no rows (if your predicate matches nothing).
461 *
462 * @param filter A filter in the same format used by a sql WHERE clause. The
463 * filter must not be empty.
464 *
465 * @examples
466 *
467 * ```ts
468 * const con = await lancedb.connect("./.lancedb")
469 * const data = [
470 * {id: 1, vector: [1, 2]},
471 * {id: 2, vector: [3, 4]},
472 * {id: 3, vector: [5, 6]},
473 * ];
474 * const tbl = await con.createTable("my_table", data)
475 * await tbl.delete("id = 2")
476 * await tbl.countRows() // Returns 2
477 * ```
478 *
479 * If you have a list of values to delete, you can combine them into a
480 * stringified list and use the `IN` operator:
481 *
482 * ```ts
483 * const to_remove = [1, 5];
484 * await tbl.delete(`id IN (${to_remove.join(",")})`)
485 * await tbl.countRows() // Returns 1
486 * ```
487 */
488 delete: (filter: string) => Promise<void>
489
490 /**
491 * Update rows in this table.
492 *
493 * This can be used to update a single row, many rows, all rows, or
494 * sometimes no rows (if your predicate matches nothing).
495 *
496 * @param args see {@link UpdateArgs} and {@link UpdateSqlArgs} for more details
497 *
498 * @examples
499 *
500 * ```ts
501 * const con = await lancedb.connect("./.lancedb")
502 * const data = [
503 * {id: 1, vector: [3, 3], name: 'Ye'},
504 * {id: 2, vector: [4, 4], name: 'Mike'},
505 * ];
506 * const tbl = await con.createTable("my_table", data)
507 *
508 * await tbl.update({
509 * where: "id = 2",
510 * values: { vector: [2, 2], name: "Michael" },
511 * })
512 *
513 * let results = await tbl.search([1, 1]).execute();
514 * // Returns [
515 * // {id: 2, vector: [2, 2], name: 'Michael'}
516 * // {id: 1, vector: [3, 3], name: 'Ye'}
517 * // ]
518 * ```
519 *
520 */
521 update: (args: UpdateArgs | UpdateSqlArgs) => Promise<void>
522
523 /**
524 * Runs a "merge insert" operation on the table
525 *
526 * This operation can add rows, update rows, and remove rows all in a single
527 * transaction. It is a very generic tool that can be used to create
528 * behaviors like "insert if not exists", "update or insert (i.e. upsert)",
529 * or even replace a portion of existing data with new data (e.g. replace
530 * all data where month="january")
531 *
532 * The merge insert operation works by combining new data from a
533 * **source table** with existing data in a **target table** by using a
534 * join. There are three categories of records.
535 *
536 * "Matched" records are records that exist in both the source table and
537 * the target table. "Not matched" records exist only in the source table
538 * (e.g. these are new data) "Not matched by source" records exist only
539 * in the target table (this is old data)
540 *
541 * The MergeInsertArgs can be used to customize what should happen for
542 * each category of data.
543 *
544 * Please note that the data may appear to be reordered as part of this
545 * operation. This is because updated rows will be deleted from the
546 * dataset and then reinserted at the end with the new values.
547 *
548 * @param on a column to join on. This is how records from the source
549 * table and target table are matched.
550 * @param data the new data to insert
551 * @param args parameters controlling how the operation should behave
552 */
553 mergeInsert: (
554 on: string,
555 data: Array<Record<string, unknown>> | ArrowTable,
556 args: MergeInsertArgs
557 ) => Promise<void>
558
559 /**
560 * List the indicies on this table.
561 */
562 listIndices: () => Promise<VectorIndex[]>
563
564 /**
565 * Get statistics about an index.
566 */
567 indexStats: (indexName: string) => Promise<IndexStats>
568
569 filter(value: string): Query<T>
570
571 schema: Promise<Schema>
572
573 // TODO: Support BatchUDF
574 /**
575 * Add new columns with defined values.
576 *
577 * @param newColumnTransforms pairs of column names and the SQL expression to use
578 * to calculate the value of the new column. These
579 * expressions will be evaluated for each row in the
580 * table, and can reference existing columns in the table.
581 */
582 addColumns(
583 newColumnTransforms: Array<{ name: string, valueSql: string }>
584 ): Promise<void>
585
586 /**
587 * Alter the name or nullability of columns.
588 *
589 * @param columnAlterations One or more alterations to apply to columns.
590 */
591 alterColumns(columnAlterations: ColumnAlteration[]): Promise<void>
592
593 /**
594 * Drop one or more columns from the dataset
595 *
596 * This is a metadata-only operation and does not remove the data from the
597 * underlying storage. In order to remove the data, you must subsequently
598 * call ``compact_files`` to rewrite the data without the removed columns and
599 * then call ``cleanup_files`` to remove the old files.
600 *
601 * @param columnNames The names of the columns to drop. These can be nested
602 * column references (e.g. "a.b.c") or top-level column
603 * names (e.g. "a").
604 */
605 dropColumns(columnNames: string[]): Promise<void>
606
607 /**
608 * Instrument the behavior of this Table with middleware.
609 *
610 * The middleware will be called in the order they are added.
611 *
612 * Currently this functionality is only supported for remote tables.
613 *
614 * @param {HttpMiddleware} - Middleware which will instrument the Table.
615 * @returns - this Table instrumented by the passed middleware
616 */
617 withMiddleware(middleware: HttpMiddleware): Table<T>
618}
619
620/**
621 * A definition of a column alteration. The alteration changes the column at
622 * `path` to have the new name `name`, to be nullable if `nullable` is true,
623 * and to have the data type `data_type`. At least one of `rename` or `nullable`
624 * must be provided.
625 */
626export interface ColumnAlteration {
627 /**
628 * The path to the column to alter. This is a dot-separated path to the column.
629 * If it is a top-level column then it is just the name of the column. If it is
630 * a nested column then it is the path to the column, e.g. "a.b.c" for a column
631 * `c` nested inside a column `b` nested inside a column `a`.
632 */
633 path: string
634 rename?: string
635 /**
636 * Set the new nullability. Note that a nullable column cannot be made non-nullable.
637 */
638 nullable?: boolean
639}
640
641export interface UpdateArgs {
642 /**
643 * A filter in the same format used by a sql WHERE clause. The filter may be empty,
644 * in which case all rows will be updated.
645 */
646 where?: string
647
648 /**
649 * A key-value map of updates. The keys are the column names, and the values are the
650 * new values to set
651 */
652 values: Record<string, Literal>
653}
654
655export interface UpdateSqlArgs {
656 /**
657 * A filter in the same format used by a sql WHERE clause. The filter may be empty,
658 * in which case all rows will be updated.
659 */
660 where?: string
661
662 /**
663 * A key-value map of updates. The keys are the column names, and the values are the
664 * new values to set as SQL expressions.
665 */
666 valuesSql: Record<string, string>
667}
668
669export interface MergeInsertArgs {
670 /**
671 * If true then rows that exist in both the source table (new data) and
672 * the target table (old data) will be updated, replacing the old row
673 * with the corresponding matching row.
674 *
675 * If there are multiple matches then the behavior is undefined.
676 * Currently this causes multiple copies of the row to be created
677 * but that behavior is subject to change.
678 *
679 * Optionally, a filter can be specified. This should be an SQL
680 * filter where fields with the prefix "target." refer to fields
681 * in the target table (old data) and fields with the prefix
682 * "source." refer to fields in the source table (new data). For
683 * example, the filter "target.lastUpdated < source.lastUpdated" will
684 * only update matched rows when the incoming `lastUpdated` value is
685 * newer.
686 *
687 * Rows that do not match the filter will not be updated. Rows that
688 * do not match the filter do become "not matched" rows.
689 */
690 whenMatchedUpdateAll?: string | boolean
691 /**
692 * If true then rows that exist only in the source table (new data)
693 * will be inserted into the target table.
694 */
695 whenNotMatchedInsertAll?: boolean
696 /**
697 * If true then rows that exist only in the target table (old data)
698 * will be deleted.
699 *
700 * If this is a string then it will be treated as an SQL filter and
701 * only rows that both do not match any row in the source table and
702 * match the given filter will be deleted.
703 *
704 * This can be used to replace a selection of existing data with
705 * new data.
706 */
707 whenNotMatchedBySourceDelete?: string | boolean
708}
709
710export enum IndexStatus {
711 Pending = "pending",
712 Indexing = "indexing",
713 Done = "done",
714 Failed = "failed"
715}
716
717export interface VectorIndex {
718 columns: string[]
719 name: string
720 uuid: string
721 status: IndexStatus
722}
723
724export interface IndexStats {
725 numIndexedRows: number | null
726 numUnindexedRows: number | null
727 indexType: string
728 distanceType?: string
729 numIndices?: number
730}
731
732/**
733 * A connection to a LanceDB database.
734 */
735export class LocalConnection implements Connection {
736 private readonly _options: () => ConnectionOptions;
737 private readonly _db: any;
738
739 constructor(db: any, options: ConnectionOptions) {
740 this._options = () => options;
741 this._db = db;
742 }
743
744 get uri(): string {
745 return this._options().uri;
746 }
747
748 /**
749 * Get the names of all tables in the database.
750 */
751 async tableNames(): Promise<string[]> {
752 return databaseTableNames.call(this._db);
753 }
754
755 /**
756 * Open a table in the database.
757 *
758 * @param name The name of the table.
759 */
760 async openTable(name: string): Promise<Table>;
761
762 /**
763 * Open a table in the database.
764 *
765 * @param name The name of the table.
766 * @param embeddings An embedding function to use on this Table
767 */
768 async openTable<T>(
769 name: string,
770 embeddings: EmbeddingFunction<T>
771 ): Promise<Table<T>>;
772 async openTable<T>(
773 name: string,
774 embeddings?: EmbeddingFunction<T>
775 ): Promise<Table<T>>;
776 async openTable<T>(
777 name: string,
778 embeddings?: EmbeddingFunction<T>
779 ): Promise<Table<T>> {
780 const tbl = await databaseOpenTable.call(this._db, name);
781 if (embeddings !== undefined) {
782 return new LocalTable(tbl, name, this._options(), embeddings);
783 } else {
784 return new LocalTable(tbl, name, this._options());
785 }
786 }
787
788 async createTable<T>(
789 name: string | CreateTableOptions<T>,
790 data?: Array<Record<string, unknown>> | ArrowTable,
791 optsOrEmbedding?: WriteOptions | EmbeddingFunction<T>,
792 opt?: WriteOptions
793 ): Promise<Table<T>> {
794 if (typeof name === "string") {
795 let writeOptions: WriteOptions = new DefaultWriteOptions();
796 if (opt !== undefined && isWriteOptions(opt)) {
797 writeOptions = opt;
798 } else if (
799 optsOrEmbedding !== undefined &&
800 isWriteOptions(optsOrEmbedding)
801 ) {
802 writeOptions = optsOrEmbedding;
803 }
804
805 let embeddings: undefined | EmbeddingFunction<T>;
806 if (
807 optsOrEmbedding !== undefined &&
808 isEmbeddingFunction(optsOrEmbedding)
809 ) {
810 embeddings = optsOrEmbedding;
811 }
812 return await this.createTableImpl({
813 name,
814 data,
815 embeddingFunction: embeddings,
816 writeOptions
817 });
818 }
819 return await this.createTableImpl(name);
820 }
821
822 private async createTableImpl<T>({
823 name,
824 data,
825 schema,
826 embeddingFunction,
827 writeOptions = new DefaultWriteOptions()
828 }: {
829 name: string
830 data?: Array<Record<string, unknown>> | ArrowTable | undefined
831 schema?: Schema | undefined
832 embeddingFunction?: EmbeddingFunction<T> | undefined
833 writeOptions?: WriteOptions | undefined
834 }): Promise<Table<T>> {
835 let buffer: Buffer;
836
837 function isEmpty(
838 data: Array<Record<string, unknown>> | ArrowTable<any>
839 ): boolean {
840 if (data instanceof ArrowTable) {
841 return data.data.length === 0;
842 }
843 return data.length === 0;
844 }
845
846 if (data === undefined || isEmpty(data)) {
847 if (schema === undefined) {
848 throw new Error("Either data or schema needs to defined");
849 }
850 buffer = await fromTableToBuffer(createEmptyTable(schema));
851 } else if (data instanceof ArrowTable) {
852 buffer = await fromTableToBuffer(data, embeddingFunction, schema);
853 } else {
854 // data is Array<Record<...>>
855 buffer = await fromRecordsToBuffer(data, embeddingFunction, schema);
856 }
857
858 const tbl = await tableCreate.call(
859 this._db,
860 name,
861 buffer,
862 writeOptions?.writeMode?.toString(),
863 ...getAwsArgs(this._options())
864 );
865 if (embeddingFunction !== undefined) {
866 return new LocalTable(tbl, name, this._options(), embeddingFunction);
867 } else {
868 return new LocalTable(tbl, name, this._options());
869 }
870 }
871
872 /**
873 * Drop an existing table.
874 * @param name The name of the table to drop.
875 */
876 async dropTable(name: string): Promise<void> {
877 await databaseDropTable.call(this._db, name);
878 }
879
880 withMiddleware(middleware: HttpMiddleware): Connection {
881 return this;
882 }
883}
884
885export class LocalTable<T = number[]> implements Table<T> {
886 private _tbl: any;
887 private readonly _name: string;
888 private readonly _isElectron: boolean;
889 private readonly _embeddings?: EmbeddingFunction<T>;
890 private readonly _options: () => ConnectionOptions;
891
892 constructor(tbl: any, name: string, options: ConnectionOptions);
893 /**
894 * @param tbl
895 * @param name
896 * @param options
897 * @param embeddings An embedding function to use when interacting with this table
898 */
899 constructor(
900 tbl: any,
901 name: string,
902 options: ConnectionOptions,
903 embeddings: EmbeddingFunction<T>
904 );
905 constructor(
906 tbl: any,
907 name: string,
908 options: ConnectionOptions,
909 embeddings?: EmbeddingFunction<T>
910 ) {
911 this._tbl = tbl;
912 this._name = name;
913 this._embeddings = embeddings;
914 this._options = () => options;
915 this._isElectron = this.checkElectron();
916 }
917
918 get name(): string {
919 return this._name;
920 }
921
922 /**
923 * Creates a search query to find the nearest neighbors of the given search term
924 * @param query The query search term
925 */
926 search(query: T): Query<T> {
927 return new Query(query, this._tbl, this._embeddings);
928 }
929
930 /**
931 * Creates a filter query to find all rows matching the specified criteria
932 * @param value The filter criteria (like SQL where clause syntax)
933 */
934 filter(value: string): Query<T> {
935 return new Query(undefined, this._tbl, this._embeddings).filter(value);
936 }
937
938 where = this.filter;
939
940 /**
941 * Insert records into this Table.
942 *
943 * @param data Records to be inserted into the Table
944 * @return The number of rows added to the table
945 */
946 async add(
947 data: Array<Record<string, unknown>> | ArrowTable
948 ): Promise<number> {
949 const schema = await this.schema;
950
951 let tbl: ArrowTable;
952
953 if (data instanceof ArrowTable) {
954 tbl = data;
955 } else {
956 tbl = makeArrowTable(data, { schema, embeddings: this._embeddings });
957 }
958
959 return tableAdd
960 .call(
961 this._tbl,
962 await fromTableToBuffer(tbl, this._embeddings, schema),
963 WriteMode.Append.toString(),
964 ...getAwsArgs(this._options())
965 )
966 .then((newTable: any) => {
967 this._tbl = newTable;
968 });
969 }
970
971 /**
972 * Insert records into this Table, replacing its contents.
973 *
974 * @param data Records to be inserted into the Table
975 * @return The number of rows added to the table
976 */
977 async overwrite(
978 data: Array<Record<string, unknown>> | ArrowTable
979 ): Promise<number> {
980 let buffer: Buffer;
981 if (data instanceof ArrowTable) {
982 buffer = await fromTableToBuffer(data, this._embeddings);
983 } else {
984 buffer = await fromRecordsToBuffer(data, this._embeddings);
985 }
986 return tableAdd
987 .call(
988 this._tbl,
989 buffer,
990 WriteMode.Overwrite.toString(),
991 ...getAwsArgs(this._options())
992 )
993 .then((newTable: any) => {
994 this._tbl = newTable;
995 });
996 }
997
998 /**
999 * Create an ANN index on this Table vector index.
1000 *
1001 * @param indexParams The parameters of this Index, @see VectorIndexParams.
1002 */
1003 async createIndex(indexParams: VectorIndexParams): Promise<any> {
1004 return tableCreateVectorIndex
1005 .call(this._tbl, indexParams)
1006 .then((newTable: any) => {
1007 this._tbl = newTable;
1008 });
1009 }
1010
1011 async createScalarIndex(column: string, replace?: boolean): Promise<void> {
1012 if (replace === undefined) {
1013 replace = true;
1014 }
1015 return tableCreateScalarIndex.call(this._tbl, column, replace);
1016 }
1017
1018 /**
1019 * Returns the number of rows in this table.
1020 */
1021 async countRows(filter?: string): Promise<number> {
1022 return tableCountRows.call(this._tbl, filter);
1023 }
1024
1025 /**
1026 * Delete rows from this table.
1027 *
1028 * @param filter A filter in the same format used by a sql WHERE clause.
1029 */
1030 async delete(filter: string): Promise<void> {
1031 return tableDelete.call(this._tbl, filter).then((newTable: any) => {
1032 this._tbl = newTable;
1033 });
1034 }
1035
1036 /**
1037 * Update rows in this table.
1038 *
1039 * @param args see {@link UpdateArgs} and {@link UpdateSqlArgs} for more details
1040 *
1041 * @returns
1042 */
1043 async update(args: UpdateArgs | UpdateSqlArgs): Promise<void> {
1044 let filter: string | null;
1045 let updates: Record<string, string>;
1046
1047 if ("valuesSql" in args) {
1048 filter = args.where ?? null;
1049 updates = args.valuesSql;
1050 } else {
1051 filter = args.where ?? null;
1052 updates = {};
1053 for (const [key, value] of Object.entries(args.values)) {
1054 updates[key] = toSQL(value);
1055 }
1056 }
1057
1058 return tableUpdate
1059 .call(this._tbl, filter, updates)
1060 .then((newTable: any) => {
1061 this._tbl = newTable;
1062 });
1063 }
1064
1065 async mergeInsert(
1066 on: string,
1067 data: Array<Record<string, unknown>> | ArrowTable,
1068 args: MergeInsertArgs
1069 ): Promise<void> {
1070 let whenMatchedUpdateAll = false;
1071 let whenMatchedUpdateAllFilt = null;
1072 if (
1073 args.whenMatchedUpdateAll !== undefined &&
1074 args.whenMatchedUpdateAll !== null
1075 ) {
1076 whenMatchedUpdateAll = true;
1077 if (args.whenMatchedUpdateAll !== true) {
1078 whenMatchedUpdateAllFilt = args.whenMatchedUpdateAll;
1079 }
1080 }
1081 const whenNotMatchedInsertAll = args.whenNotMatchedInsertAll ?? false;
1082 let whenNotMatchedBySourceDelete = false;
1083 let whenNotMatchedBySourceDeleteFilt = null;
1084 if (
1085 args.whenNotMatchedBySourceDelete !== undefined &&
1086 args.whenNotMatchedBySourceDelete !== null
1087 ) {
1088 whenNotMatchedBySourceDelete = true;
1089 if (args.whenNotMatchedBySourceDelete !== true) {
1090 whenNotMatchedBySourceDeleteFilt = args.whenNotMatchedBySourceDelete;
1091 }
1092 }
1093
1094 const schema = await this.schema;
1095 let tbl: ArrowTable;
1096 if (data instanceof ArrowTable) {
1097 tbl = data;
1098 } else {
1099 tbl = makeArrowTable(data, { schema });
1100 }
1101 const buffer = await fromTableToBuffer(tbl, this._embeddings, schema);
1102
1103 this._tbl = await tableMergeInsert.call(
1104 this._tbl,
1105 on,
1106 whenMatchedUpdateAll,
1107 whenMatchedUpdateAllFilt,
1108 whenNotMatchedInsertAll,
1109 whenNotMatchedBySourceDelete,
1110 whenNotMatchedBySourceDeleteFilt,
1111 buffer
1112 );
1113 }
1114
1115 /**
1116 * Clean up old versions of the table, freeing disk space.
1117 *
1118 * @param olderThan The minimum age in minutes of the versions to delete. If not
1119 * provided, defaults to two weeks.
1120 * @param deleteUnverified Because they may be part of an in-progress
1121 * transaction, uncommitted files newer than 7 days old are
1122 * not deleted by default. This means that failed transactions
1123 * can leave around data that takes up disk space for up to
1124 * 7 days. You can override this safety mechanism by setting
1125 * this option to `true`, only if you promise there are no
1126 * in progress writes while you run this operation. Failure to
1127 * uphold this promise can lead to corrupted tables.
1128 * @returns
1129 */
1130 async cleanupOldVersions(
1131 olderThan?: number,
1132 deleteUnverified?: boolean
1133 ): Promise<CleanupStats> {
1134 return tableCleanupOldVersions
1135 .call(this._tbl, olderThan, deleteUnverified)
1136 .then((res: { newTable: any, metrics: CleanupStats }) => {
1137 this._tbl = res.newTable;
1138 return res.metrics;
1139 });
1140 }
1141
1142 /**
1143 * Run the compaction process on the table.
1144 *
1145 * This can be run after making several small appends to optimize the table
1146 * for faster reads.
1147 *
1148 * @param options Advanced options configuring compaction. In most cases, you
1149 * can omit this arguments, as the default options are sensible
1150 * for most tables.
1151 * @returns Metrics about the compaction operation.
1152 */
1153 async compactFiles(options?: CompactionOptions): Promise<CompactionMetrics> {
1154 const optionsArg = options ?? {};
1155 return tableCompactFiles
1156 .call(this._tbl, optionsArg)
1157 .then((res: { newTable: any, metrics: CompactionMetrics }) => {
1158 this._tbl = res.newTable;
1159 return res.metrics;
1160 });
1161 }
1162
1163 async listIndices(): Promise<VectorIndex[]> {
1164 return tableListIndices.call(this._tbl);
1165 }
1166
1167 async indexStats(indexName: string): Promise<IndexStats> {
1168 return tableIndexStats.call(this._tbl, indexName);
1169 }
1170
1171 get schema(): Promise<Schema> {
1172 // empty table
1173 return this.getSchema();
1174 }
1175
1176 private async getSchema(): Promise<Schema> {
1177 const buffer = await tableSchema.call(this._tbl, this._isElectron);
1178 const table = tableFromIPC(buffer);
1179 return table.schema;
1180 }
1181
1182 // See https://github.com/electron/electron/issues/2288
1183 private checkElectron(): boolean {
1184 try {
1185 // eslint-disable-next-line no-prototype-builtins
1186 return (
1187 Object.prototype.hasOwnProperty.call(process?.versions, "electron") ||
1188 navigator?.userAgent?.toLowerCase()?.includes(" electron")
1189 );
1190 } catch (e) {
1191 return false;
1192 }
1193 }
1194
1195 async addColumns(
1196 newColumnTransforms: Array<{ name: string, valueSql: string }>
1197 ): Promise<void> {
1198 return tableAddColumns.call(this._tbl, newColumnTransforms);
1199 }
1200
1201 async alterColumns(columnAlterations: ColumnAlteration[]): Promise<void> {
1202 return tableAlterColumns.call(this._tbl, columnAlterations);
1203 }
1204
1205 async dropColumns(columnNames: string[]): Promise<void> {
1206 return tableDropColumns.call(this._tbl, columnNames);
1207 }
1208
1209 withMiddleware(middleware: HttpMiddleware): Table<T> {
1210 return this;
1211 }
1212}
1213
1214export interface CleanupStats {
1215 /**
1216 * The number of bytes removed from disk.
1217 */
1218 bytesRemoved: number
1219 /**
1220 * The number of old table versions removed.
1221 */
1222 oldVersions: number
1223}
1224
1225export interface CompactionOptions {
1226 /**
1227 * The number of rows per fragment to target. Fragments that have fewer rows
1228 * will be compacted into adjacent fragments to produce larger fragments.
1229 * Defaults to 1024 * 1024.
1230 */
1231 targetRowsPerFragment?: number
1232 /**
1233 * The maximum number of T per group. Defaults to 1024.
1234 */
1235 maxRowsPerGroup?: number
1236 /**
1237 * If true, fragments that have rows that are deleted may be compacted to
1238 * remove the deleted rows. This can improve the performance of queries.
1239 * Default is true.
1240 */
1241 materializeDeletions?: boolean
1242 /**
1243 * A number between 0 and 1, representing the proportion of rows that must be
1244 * marked deleted before a fragment is a candidate for compaction to remove
1245 * the deleted rows. Default is 10%.
1246 */
1247 materializeDeletionsThreshold?: number
1248 /**
1249 * The number of threads to use for compaction. If not provided, defaults to
1250 * the number of cores on the machine.
1251 */
1252 numThreads?: number
1253}
1254
1255export interface CompactionMetrics {
1256 /**
1257 * The number of fragments that were removed.
1258 */
1259 fragmentsRemoved: number
1260 /**
1261 * The number of new fragments that were created.
1262 */
1263 fragmentsAdded: number
1264 /**
1265 * The number of files that were removed. Each fragment may have more than one
1266 * file.
1267 */
1268 filesRemoved: number
1269 /**
1270 * The number of files added. This is typically equal to the number of
1271 * fragments added.
1272 */
1273 filesAdded: number
1274}
1275
1276/// Config to build IVF_PQ index.
1277///
1278export interface IvfPQIndexConfig {
1279 /**
1280 * The column to be indexed
1281 */
1282 column?: string
1283
1284 /**
1285 * A unique name for the index
1286 */
1287 index_name?: string
1288
1289 /**
1290 * Metric type, L2 or Cosine
1291 */
1292 metric_type?: MetricType
1293
1294 /**
1295 * The number of partitions this index
1296 */
1297 num_partitions?: number
1298
1299 /**
1300 * The max number of iterations for kmeans training.
1301 */
1302 max_iters?: number
1303
1304 /**
1305 * Train as optimized product quantization.
1306 */
1307 use_opq?: boolean
1308
1309 /**
1310 * Number of subvectors to build PQ code
1311 */
1312 num_sub_vectors?: number
1313 /**
1314 * The number of bits to present one PQ centroid.
1315 */
1316 num_bits?: number
1317
1318 /**
1319 * Max number of iterations to train OPQ, if `use_opq` is true.
1320 */
1321 max_opq_iters?: number
1322
1323 /**
1324 * Replace an existing index with the same name if it exists.
1325 */
1326 replace?: boolean
1327
1328 /**
1329 * Cache size of the index
1330 */
1331 index_cache_size?: number
1332
1333 type: "ivf_pq"
1334}
1335
1336export type VectorIndexParams = IvfPQIndexConfig;
1337
1338/**
1339 * Write mode for writing a table.
1340 */
1341export enum WriteMode {
1342 /** Create a new {@link Table}. */
1343 Create = "create",
1344 /** Overwrite the existing {@link Table} if presented. */
1345 Overwrite = "overwrite",
1346 /** Append new data to the table. */
1347 Append = "append",
1348}
1349
1350/**
1351 * Write options when creating a Table.
1352 */
1353export interface WriteOptions {
1354 /** A {@link WriteMode} to use on this operation */
1355 writeMode?: WriteMode
1356}
1357
1358export class DefaultWriteOptions implements WriteOptions {
1359 writeMode = WriteMode.Create;
1360}
1361
1362export function isWriteOptions(value: any): value is WriteOptions {
1363 return (
1364 Object.keys(value).length === 1 &&
1365 (value.writeMode === undefined || typeof value.writeMode === "string")
1366 );
1367}
1368
1369/**
1370 * Distance metrics type.
1371 */
1372export enum MetricType {
1373 /**
1374 * Euclidean distance
1375 */
1376 L2 = "l2",
1377
1378 /**
1379 * Cosine distance
1380 */
1381 Cosine = "cosine",
1382
1383 /**
1384 * Dot product
1385 */
1386 Dot = "dot",
1387}