Elffuss BraidHub

kikocis/lancedb public

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