@lancedb/lancedb 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.eslintignore +3 -0
  2. package/Cargo.toml +28 -0
  3. package/README.md +49 -0
  4. package/build.rs +5 -0
  5. package/eslint.config.js +28 -0
  6. package/examples/js/index.mjs +40 -0
  7. package/examples/js/package.json +14 -0
  8. package/examples/js-openai/index.mjs +43 -0
  9. package/examples/js-openai/package-lock.json +256 -0
  10. package/examples/js-openai/package.json +15 -0
  11. package/examples/js-transformers/index.mjs +65 -0
  12. package/examples/js-transformers/package-lock.json +1418 -0
  13. package/examples/js-transformers/package.json +15 -0
  14. package/examples/js-youtube-transcripts/index.mjs +135 -0
  15. package/examples/js-youtube-transcripts/package.json +15 -0
  16. package/examples/ts/data/sample-lancedb/vectors.lance/_latest.manifest +0 -0
  17. package/examples/ts/data/sample-lancedb/vectors.lance/_transactions/0-adde4e05-fcfc-415c-86a6-5b252cb9e79a.txn +0 -0
  18. package/examples/ts/data/sample-lancedb/vectors.lance/_versions/1.manifest +0 -0
  19. package/examples/ts/data/sample-lancedb/vectors.lance/data/3618b33e-3eea-4b5e-a0fc-7d1f718d551e.lance +0 -0
  20. package/examples/ts/package-lock.json +1340 -0
  21. package/examples/ts/package.json +22 -0
  22. package/examples/ts/tsconfig.json +10 -0
  23. package/jest.config.js +7 -0
  24. package/lancedb/arrow.ts +650 -0
  25. package/lancedb/connection.ts +176 -0
  26. package/lancedb/embedding/embedding_function.ts +78 -0
  27. package/lancedb/embedding/index.ts +2 -0
  28. package/lancedb/embedding/openai.ts +62 -0
  29. package/lancedb/index.ts +69 -0
  30. package/lancedb/indices.ts +203 -0
  31. package/lancedb/query.ts +375 -0
  32. package/lancedb/sanitize.ts +516 -0
  33. package/lancedb/table.ts +353 -0
  34. package/package.json +82 -0
  35. package/tsconfig.json +23 -0
@@ -0,0 +1,176 @@
1
+ // Copyright 2024 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
+
15
+ import { fromTableToBuffer, makeArrowTable, makeEmptyTable } from "./arrow";
16
+ import { Connection as LanceDbConnection } from "./native";
17
+ import { Table } from "./table";
18
+ import { Table as ArrowTable, Schema } from "apache-arrow";
19
+
20
+ export interface CreateTableOptions {
21
+ /**
22
+ * The mode to use when creating the table.
23
+ *
24
+ * If this is set to "create" and the table already exists then either
25
+ * an error will be thrown or, if existOk is true, then nothing will
26
+ * happen. Any provided data will be ignored.
27
+ *
28
+ * If this is set to "overwrite" then any existing table will be replaced.
29
+ */
30
+ mode: "create" | "overwrite";
31
+ /**
32
+ * If this is true and the table already exists and the mode is "create"
33
+ * then no error will be raised.
34
+ */
35
+ existOk: boolean;
36
+ }
37
+
38
+ export interface TableNamesOptions {
39
+ /**
40
+ * If present, only return names that come lexicographically after the
41
+ * supplied value.
42
+ *
43
+ * This can be combined with limit to implement pagination by setting this to
44
+ * the last table name from the previous page.
45
+ */
46
+ startAfter?: string;
47
+ /** An optional limit to the number of results to return. */
48
+ limit?: number;
49
+ }
50
+
51
+ /**
52
+ * A LanceDB Connection that allows you to open tables and create new ones.
53
+ *
54
+ * Connection could be local against filesystem or remote against a server.
55
+ *
56
+ * A Connection is intended to be a long lived object and may hold open
57
+ * resources such as HTTP connection pools. This is generally fine and
58
+ * a single connection should be shared if it is going to be used many
59
+ * times. However, if you are finished with a connection, you may call
60
+ * close to eagerly free these resources. Any call to a Connection
61
+ * method after it has been closed will result in an error.
62
+ *
63
+ * Closing a connection is optional. Connections will automatically
64
+ * be closed when they are garbage collected.
65
+ *
66
+ * Any created tables are independent and will continue to work even if
67
+ * the underlying connection has been closed.
68
+ */
69
+ export class Connection {
70
+ readonly inner: LanceDbConnection;
71
+
72
+ constructor(inner: LanceDbConnection) {
73
+ this.inner = inner;
74
+ }
75
+
76
+ /** Return true if the connection has not been closed */
77
+ isOpen(): boolean {
78
+ return this.inner.isOpen();
79
+ }
80
+
81
+ /**
82
+ * Close the connection, releasing any underlying resources.
83
+ *
84
+ * It is safe to call this method multiple times.
85
+ *
86
+ * Any attempt to use the connection after it is closed will result in an error.
87
+ */
88
+ close(): void {
89
+ this.inner.close();
90
+ }
91
+
92
+ /** Return a brief description of the connection */
93
+ display(): string {
94
+ return this.inner.display();
95
+ }
96
+
97
+ /**
98
+ * List all the table names in this database.
99
+ *
100
+ * Tables will be returned in lexicographical order.
101
+ * @param {Partial<TableNamesOptions>} options - options to control the
102
+ * paging / start point
103
+ */
104
+ async tableNames(options?: Partial<TableNamesOptions>): Promise<string[]> {
105
+ return this.inner.tableNames(options?.startAfter, options?.limit);
106
+ }
107
+
108
+ /**
109
+ * Open a table in the database.
110
+ * @param {string} name - The name of the table
111
+ */
112
+ async openTable(name: string): Promise<Table> {
113
+ const innerTable = await this.inner.openTable(name);
114
+ return new Table(innerTable);
115
+ }
116
+
117
+ /**
118
+ * Creates a new Table and initialize it with new data.
119
+ * @param {string} name - The name of the table.
120
+ * @param {Record<string, unknown>[] | ArrowTable} data - Non-empty Array of Records
121
+ * to be inserted into the table
122
+ */
123
+ async createTable(
124
+ name: string,
125
+ data: Record<string, unknown>[] | ArrowTable,
126
+ options?: Partial<CreateTableOptions>,
127
+ ): Promise<Table> {
128
+ let mode: string = options?.mode ?? "create";
129
+ const existOk = options?.existOk ?? false;
130
+
131
+ if (mode === "create" && existOk) {
132
+ mode = "exist_ok";
133
+ }
134
+
135
+ let table: ArrowTable;
136
+ if (data instanceof ArrowTable) {
137
+ table = data;
138
+ } else {
139
+ table = makeArrowTable(data);
140
+ }
141
+ const buf = await fromTableToBuffer(table);
142
+ const innerTable = await this.inner.createTable(name, buf, mode);
143
+ return new Table(innerTable);
144
+ }
145
+
146
+ /**
147
+ * Creates a new empty Table
148
+ * @param {string} name - The name of the table.
149
+ * @param {Schema} schema - The schema of the table
150
+ */
151
+ async createEmptyTable(
152
+ name: string,
153
+ schema: Schema,
154
+ options?: Partial<CreateTableOptions>,
155
+ ): Promise<Table> {
156
+ let mode: string = options?.mode ?? "create";
157
+ const existOk = options?.existOk ?? false;
158
+
159
+ if (mode === "create" && existOk) {
160
+ mode = "exist_ok";
161
+ }
162
+
163
+ const table = makeEmptyTable(schema);
164
+ const buf = await fromTableToBuffer(table);
165
+ const innerTable = await this.inner.createEmptyTable(name, buf, mode);
166
+ return new Table(innerTable);
167
+ }
168
+
169
+ /**
170
+ * Drop an existing table.
171
+ * @param {string} name The name of the table to drop.
172
+ */
173
+ async dropTable(name: string): Promise<void> {
174
+ return this.inner.dropTable(name);
175
+ }
176
+ }
@@ -0,0 +1,78 @@
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
+
15
+ import { type Float } from "apache-arrow";
16
+
17
+ /**
18
+ * An embedding function that automatically creates vector representation for a given column.
19
+ */
20
+ export interface EmbeddingFunction<T> {
21
+ /**
22
+ * The name of the column that will be used as input for the Embedding Function.
23
+ */
24
+ sourceColumn: string;
25
+
26
+ /**
27
+ * The data type of the embedding
28
+ *
29
+ * The embedding function should return `number`. This will be converted into
30
+ * an Arrow float array. By default this will be Float32 but this property can
31
+ * be used to control the conversion.
32
+ */
33
+ embeddingDataType?: Float;
34
+
35
+ /**
36
+ * The dimension of the embedding
37
+ *
38
+ * This is optional, normally this can be determined by looking at the results of
39
+ * `embed`. If this is not specified, and there is an attempt to apply the embedding
40
+ * to an empty table, then that process will fail.
41
+ */
42
+ embeddingDimension?: number;
43
+
44
+ /**
45
+ * The name of the column that will contain the embedding
46
+ *
47
+ * By default this is "vector"
48
+ */
49
+ destColumn?: string;
50
+
51
+ /**
52
+ * Should the source column be excluded from the resulting table
53
+ *
54
+ * By default the source column is included. Set this to true and
55
+ * only the embedding will be stored.
56
+ */
57
+ excludeSource?: boolean;
58
+
59
+ /**
60
+ * Creates a vector representation for the given values.
61
+ */
62
+ embed: (data: T[]) => Promise<number[][]>;
63
+ }
64
+
65
+ /** Test if the input seems to be an embedding function */
66
+ export function isEmbeddingFunction<T>(
67
+ value: unknown,
68
+ ): value is EmbeddingFunction<T> {
69
+ if (typeof value !== "object" || value === null) {
70
+ return false;
71
+ }
72
+ if (!("sourceColumn" in value) || !("embed" in value)) {
73
+ return false;
74
+ }
75
+ return (
76
+ typeof value.sourceColumn === "string" && typeof value.embed === "function"
77
+ );
78
+ }
@@ -0,0 +1,2 @@
1
+ export { EmbeddingFunction, isEmbeddingFunction } from "./embedding_function";
2
+ export { OpenAIEmbeddingFunction } from "./openai";
@@ -0,0 +1,62 @@
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
+
15
+ import { type EmbeddingFunction } from "./embedding_function";
16
+ import type OpenAI from "openai";
17
+
18
+ export class OpenAIEmbeddingFunction implements EmbeddingFunction<string> {
19
+ private readonly _openai: OpenAI;
20
+ private readonly _modelName: string;
21
+
22
+ constructor(
23
+ sourceColumn: string,
24
+ openAIKey: string,
25
+ modelName: string = "text-embedding-ada-002",
26
+ ) {
27
+ /**
28
+ * @type {import("openai").default}
29
+ */
30
+ // eslint-disable-next-line @typescript-eslint/naming-convention
31
+ let Openai;
32
+ try {
33
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
34
+ Openai = require("openai");
35
+ } catch {
36
+ throw new Error("please install openai@^4.24.1 using npm install openai");
37
+ }
38
+
39
+ this.sourceColumn = sourceColumn;
40
+ const configuration = {
41
+ apiKey: openAIKey,
42
+ };
43
+
44
+ this._openai = new Openai(configuration);
45
+ this._modelName = modelName;
46
+ }
47
+
48
+ async embed(data: string[]): Promise<number[][]> {
49
+ const response = await this._openai.embeddings.create({
50
+ model: this._modelName,
51
+ input: data,
52
+ });
53
+
54
+ const embeddings: number[][] = [];
55
+ for (let i = 0; i < response.data.length; i++) {
56
+ embeddings.push(response.data[i].embedding);
57
+ }
58
+ return embeddings;
59
+ }
60
+
61
+ sourceColumn: string;
62
+ }
@@ -0,0 +1,69 @@
1
+ // Copyright 2024 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
+
15
+ import { Connection } from "./connection";
16
+ import {
17
+ Connection as LanceDbConnection,
18
+ ConnectionOptions,
19
+ } from "./native.js";
20
+
21
+ export {
22
+ WriteOptions,
23
+ WriteMode,
24
+ AddColumnsSql,
25
+ ColumnAlteration,
26
+ ConnectionOptions,
27
+ } from "./native.js";
28
+ export {
29
+ makeArrowTable,
30
+ MakeArrowTableOptions,
31
+ Data,
32
+ VectorColumnOptions,
33
+ } from "./arrow";
34
+ export {
35
+ Connection,
36
+ CreateTableOptions,
37
+ TableNamesOptions,
38
+ } from "./connection";
39
+ export {
40
+ ExecutableQuery,
41
+ Query,
42
+ QueryBase,
43
+ VectorQuery,
44
+ RecordBatchIterator,
45
+ } from "./query";
46
+ export { Index, IndexOptions, IvfPqOptions } from "./indices";
47
+ export { Table, AddDataOptions, IndexConfig, UpdateOptions } from "./table";
48
+ export * as embedding from "./embedding";
49
+
50
+ /**
51
+ * Connect to a LanceDB instance at the given URI.
52
+ *
53
+ * Accpeted formats:
54
+ *
55
+ * - `/path/to/database` - local database
56
+ * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
57
+ * - `db://host:port` - remote database (LanceDB cloud)
58
+ * @param {string} uri - The uri of the database. If the database uri starts
59
+ * with `db://` then it connects to a remote database.
60
+ * @see {@link ConnectionOptions} for more details on the URI format.
61
+ */
62
+ export async function connect(
63
+ uri: string,
64
+ opts?: Partial<ConnectionOptions>,
65
+ ): Promise<Connection> {
66
+ opts = opts ?? {};
67
+ const nativeConn = await LanceDbConnection.new(uri, opts);
68
+ return new Connection(nativeConn);
69
+ }
@@ -0,0 +1,203 @@
1
+ // Copyright 2024 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
+
15
+ import { Index as LanceDbIndex } from "./native";
16
+
17
+ /**
18
+ * Options to create an `IVF_PQ` index
19
+ */
20
+ export interface IvfPqOptions {
21
+ /**
22
+ * The number of IVF partitions to create.
23
+ *
24
+ * This value should generally scale with the number of rows in the dataset.
25
+ * By default the number of partitions is the square root of the number of
26
+ * rows.
27
+ *
28
+ * If this value is too large then the first part of the search (picking the
29
+ * right partition) will be slow. If this value is too small then the second
30
+ * part of the search (searching within a partition) will be slow.
31
+ */
32
+ numPartitions?: number;
33
+
34
+ /**
35
+ * Number of sub-vectors of PQ.
36
+ *
37
+ * This value controls how much the vector is compressed during the quantization step.
38
+ * The more sub vectors there are the less the vector is compressed. The default is
39
+ * the dimension of the vector divided by 16. If the dimension is not evenly divisible
40
+ * by 16 we use the dimension divded by 8.
41
+ *
42
+ * The above two cases are highly preferred. Having 8 or 16 values per subvector allows
43
+ * us to use efficient SIMD instructions.
44
+ *
45
+ * If the dimension is not visible by 8 then we use 1 subvector. This is not ideal and
46
+ * will likely result in poor performance.
47
+ */
48
+ numSubVectors?: number;
49
+
50
+ /**
51
+ * Distance type to use to build the index.
52
+ *
53
+ * Default value is "l2".
54
+ *
55
+ * This is used when training the index to calculate the IVF partitions
56
+ * (vectors are grouped in partitions with similar vectors according to this
57
+ * distance type) and to calculate a subvector's code during quantization.
58
+ *
59
+ * The distance type used to train an index MUST match the distance type used
60
+ * to search the index. Failure to do so will yield inaccurate results.
61
+ *
62
+ * The following distance types are available:
63
+ *
64
+ * "l2" - Euclidean distance. This is a very common distance metric that
65
+ * accounts for both magnitude and direction when determining the distance
66
+ * between vectors. L2 distance has a range of [0, ∞).
67
+ *
68
+ * "cosine" - Cosine distance. Cosine distance is a distance metric
69
+ * calculated from the cosine similarity between two vectors. Cosine
70
+ * similarity is a measure of similarity between two non-zero vectors of an
71
+ * inner product space. It is defined to equal the cosine of the angle
72
+ * between them. Unlike L2, the cosine distance is not affected by the
73
+ * magnitude of the vectors. Cosine distance has a range of [0, 2].
74
+ *
75
+ * Note: the cosine distance is undefined when one (or both) of the vectors
76
+ * are all zeros (there is no direction). These vectors are invalid and may
77
+ * never be returned from a vector search.
78
+ *
79
+ * "dot" - Dot product. Dot distance is the dot product of two vectors. Dot
80
+ * distance has a range of (-∞, ∞). If the vectors are normalized (i.e. their
81
+ * L2 norm is 1), then dot distance is equivalent to the cosine distance.
82
+ */
83
+ distanceType?: "l2" | "cosine" | "dot";
84
+
85
+ /**
86
+ * Max iteration to train IVF kmeans.
87
+ *
88
+ * When training an IVF PQ index we use kmeans to calculate the partitions. This parameter
89
+ * controls how many iterations of kmeans to run.
90
+ *
91
+ * Increasing this might improve the quality of the index but in most cases these extra
92
+ * iterations have diminishing returns.
93
+ *
94
+ * The default value is 50.
95
+ */
96
+ maxIterations?: number;
97
+
98
+ /**
99
+ * The number of vectors, per partition, to sample when training IVF kmeans.
100
+ *
101
+ * When an IVF PQ index is trained, we need to calculate partitions. These are groups
102
+ * of vectors that are similar to each other. To do this we use an algorithm called kmeans.
103
+ *
104
+ * Running kmeans on a large dataset can be slow. To speed this up we run kmeans on a
105
+ * random sample of the data. This parameter controls the size of the sample. The total
106
+ * number of vectors used to train the index is `sample_rate * num_partitions`.
107
+ *
108
+ * Increasing this value might improve the quality of the index but in most cases the
109
+ * default should be sufficient.
110
+ *
111
+ * The default value is 256.
112
+ */
113
+ sampleRate?: number;
114
+ }
115
+
116
+ export class Index {
117
+ private readonly inner: LanceDbIndex;
118
+ private constructor(inner: LanceDbIndex) {
119
+ this.inner = inner;
120
+ }
121
+
122
+ /**
123
+ * Create an IvfPq index
124
+ *
125
+ * This index stores a compressed (quantized) copy of every vector. These vectors
126
+ * are grouped into partitions of similar vectors. Each partition keeps track of
127
+ * a centroid which is the average value of all vectors in the group.
128
+ *
129
+ * During a query the centroids are compared with the query vector to find the closest
130
+ * partitions. The compressed vectors in these partitions are then searched to find
131
+ * the closest vectors.
132
+ *
133
+ * The compression scheme is called product quantization. Each vector is divided into
134
+ * subvectors and then each subvector is quantized into a small number of bits. the
135
+ * parameters `num_bits` and `num_subvectors` control this process, providing a tradeoff
136
+ * between index size (and thus search speed) and index accuracy.
137
+ *
138
+ * The partitioning process is called IVF and the `num_partitions` parameter controls how
139
+ * many groups to create.
140
+ *
141
+ * Note that training an IVF PQ index on a large dataset is a slow operation and
142
+ * currently is also a memory intensive operation.
143
+ */
144
+ static ivfPq(options?: Partial<IvfPqOptions>) {
145
+ return new Index(
146
+ LanceDbIndex.ivfPq(
147
+ options?.distanceType,
148
+ options?.numPartitions,
149
+ options?.numSubVectors,
150
+ options?.maxIterations,
151
+ options?.sampleRate,
152
+ ),
153
+ );
154
+ }
155
+
156
+ /**
157
+ * Create a btree index
158
+ *
159
+ * A btree index is an index on a scalar columns. The index stores a copy of the column
160
+ * in sorted order. A header entry is created for each block of rows (currently the
161
+ * block size is fixed at 4096). These header entries are stored in a separate
162
+ * cacheable structure (a btree). To search for data the header is used to determine
163
+ * which blocks need to be read from disk.
164
+ *
165
+ * For example, a btree index in a table with 1Bi rows requires sizeof(Scalar) * 256Ki
166
+ * bytes of memory and will generally need to read sizeof(Scalar) * 4096 bytes to find
167
+ * the correct row ids.
168
+ *
169
+ * This index is good for scalar columns with mostly distinct values and does best when
170
+ * the query is highly selective.
171
+ *
172
+ * The btree index does not currently have any parameters though parameters such as the
173
+ * block size may be added in the future.
174
+ */
175
+ static btree() {
176
+ return new Index(LanceDbIndex.btree());
177
+ }
178
+ }
179
+
180
+ export interface IndexOptions {
181
+ /**
182
+ * Advanced index configuration
183
+ *
184
+ * This option allows you to specify a specfic index to create and also
185
+ * allows you to pass in configuration for training the index.
186
+ *
187
+ * See the static methods on Index for details on the various index types.
188
+ *
189
+ * If this is not supplied then column data type(s) and column statistics
190
+ * will be used to determine the most useful kind of index to create.
191
+ */
192
+ config?: Index;
193
+ /**
194
+ * Whether to replace the existing index
195
+ *
196
+ * If this is false, and another index already exists on the same columns
197
+ * and the same name, then an error will be returned. This is true even if
198
+ * that index is out of date.
199
+ *
200
+ * The default is true
201
+ */
202
+ replace?: boolean;
203
+ }