Elffuss BraidHub

kikocis/lancedb public

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