@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,375 @@
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 { RecordBatch, tableFromIPC, Table as ArrowTable } from "apache-arrow";
16
+ import {
17
+ RecordBatchIterator as NativeBatchIterator,
18
+ Query as NativeQuery,
19
+ Table as NativeTable,
20
+ VectorQuery as NativeVectorQuery,
21
+ } from "./native";
22
+ import { type IvfPqOptions } from "./indices";
23
+ export class RecordBatchIterator implements AsyncIterator<RecordBatch> {
24
+ private promisedInner?: Promise<NativeBatchIterator>;
25
+ private inner?: NativeBatchIterator;
26
+
27
+ constructor(promise?: Promise<NativeBatchIterator>) {
28
+ // TODO: check promise reliably so we dont need to pass two arguments.
29
+ this.promisedInner = promise;
30
+ }
31
+
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ async next(): Promise<IteratorResult<RecordBatch<any>>> {
34
+ if (this.inner === undefined) {
35
+ this.inner = await this.promisedInner;
36
+ }
37
+ if (this.inner === undefined) {
38
+ throw new Error("Invalid iterator state state");
39
+ }
40
+ const n = await this.inner.next();
41
+ if (n == null) {
42
+ return Promise.resolve({ done: true, value: null });
43
+ }
44
+ const tbl = tableFromIPC(n);
45
+ if (tbl.batches.length != 1) {
46
+ throw new Error("Expected only one batch");
47
+ }
48
+ return Promise.resolve({ done: false, value: tbl.batches[0] });
49
+ }
50
+ }
51
+ /* eslint-enable */
52
+
53
+ /** Common methods supported by all query types */
54
+ export class QueryBase<
55
+ NativeQueryType extends NativeQuery | NativeVectorQuery,
56
+ QueryType,
57
+ > implements AsyncIterable<RecordBatch>
58
+ {
59
+ protected constructor(protected inner: NativeQueryType) {}
60
+
61
+ /**
62
+ * A filter statement to be applied to this query.
63
+ *
64
+ * The filter should be supplied as an SQL query string. For example:
65
+ * @example
66
+ * x > 10
67
+ * y > 0 AND y < 100
68
+ * x > 5 OR y = 'test'
69
+ *
70
+ * Filtering performance can often be improved by creating a scalar index
71
+ * on the filter column(s).
72
+ */
73
+ where(predicate: string): QueryType {
74
+ this.inner.onlyIf(predicate);
75
+ return this as unknown as QueryType;
76
+ }
77
+
78
+ /**
79
+ * Return only the specified columns.
80
+ *
81
+ * By default a query will return all columns from the table. However, this can have
82
+ * a very significant impact on latency. LanceDb stores data in a columnar fashion. This
83
+ * means we can finely tune our I/O to select exactly the columns we need.
84
+ *
85
+ * As a best practice you should always limit queries to the columns that you need. If you
86
+ * pass in an array of column names then only those columns will be returned.
87
+ *
88
+ * You can also use this method to create new "dynamic" columns based on your existing columns.
89
+ * For example, you may not care about "a" or "b" but instead simply want "a + b". This is often
90
+ * seen in the SELECT clause of an SQL query (e.g. `SELECT a+b FROM my_table`).
91
+ *
92
+ * To create dynamic columns you can pass in a Map<string, string>. A column will be returned
93
+ * for each entry in the map. The key provides the name of the column. The value is
94
+ * an SQL string used to specify how the column is calculated.
95
+ *
96
+ * For example, an SQL query might state `SELECT a + b AS combined, c`. The equivalent
97
+ * input to this method would be:
98
+ * @example
99
+ * new Map([["combined", "a + b"], ["c", "c"]])
100
+ *
101
+ * Columns will always be returned in the order given, even if that order is different than
102
+ * the order used when adding the data.
103
+ *
104
+ * Note that you can pass in a `Record<string, string>` (e.g. an object literal). This method
105
+ * uses `Object.entries` which should preserve the insertion order of the object. However,
106
+ * object insertion order is easy to get wrong and `Map` is more foolproof.
107
+ */
108
+ select(
109
+ columns: string[] | Map<string, string> | Record<string, string>,
110
+ ): QueryType {
111
+ let columnTuples: [string, string][];
112
+ if (Array.isArray(columns)) {
113
+ columnTuples = columns.map((c) => [c, c]);
114
+ } else if (columns instanceof Map) {
115
+ columnTuples = Array.from(columns.entries());
116
+ } else {
117
+ columnTuples = Object.entries(columns);
118
+ }
119
+ this.inner.select(columnTuples);
120
+ return this as unknown as QueryType;
121
+ }
122
+
123
+ /**
124
+ * Set the maximum number of results to return.
125
+ *
126
+ * By default, a plain search has no limit. If this method is not
127
+ * called then every valid row from the table will be returned.
128
+ */
129
+ limit(limit: number): QueryType {
130
+ this.inner.limit(limit);
131
+ return this as unknown as QueryType;
132
+ }
133
+
134
+ protected nativeExecute(): Promise<NativeBatchIterator> {
135
+ return this.inner.execute();
136
+ }
137
+
138
+ /**
139
+ * Execute the query and return the results as an @see {@link AsyncIterator}
140
+ * of @see {@link RecordBatch}.
141
+ *
142
+ * By default, LanceDb will use many threads to calculate results and, when
143
+ * the result set is large, multiple batches will be processed at one time.
144
+ * This readahead is limited however and backpressure will be applied if this
145
+ * stream is consumed slowly (this constrains the maximum memory used by a
146
+ * single query)
147
+ *
148
+ */
149
+ protected execute(): RecordBatchIterator {
150
+ return new RecordBatchIterator(this.nativeExecute());
151
+ }
152
+
153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
154
+ [Symbol.asyncIterator](): AsyncIterator<RecordBatch<any>> {
155
+ const promise = this.nativeExecute();
156
+ return new RecordBatchIterator(promise);
157
+ }
158
+
159
+ /** Collect the results as an Arrow @see {@link ArrowTable}. */
160
+ async toArrow(): Promise<ArrowTable> {
161
+ const batches = [];
162
+ for await (const batch of this) {
163
+ batches.push(batch);
164
+ }
165
+ return new ArrowTable(batches);
166
+ }
167
+
168
+ /** Collect the results as an array of objects. */
169
+ async toArray(): Promise<unknown[]> {
170
+ const tbl = await this.toArrow();
171
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
172
+ return tbl.toArray();
173
+ }
174
+ }
175
+
176
+ /**
177
+ * An interface for a query that can be executed
178
+ *
179
+ * Supported by all query types
180
+ */
181
+ export interface ExecutableQuery {}
182
+
183
+ /**
184
+ * A builder used to construct a vector search
185
+ *
186
+ * This builder can be reused to execute the query many times.
187
+ */
188
+ export class VectorQuery extends QueryBase<NativeVectorQuery, VectorQuery> {
189
+ constructor(inner: NativeVectorQuery) {
190
+ super(inner);
191
+ }
192
+
193
+ /**
194
+ * Set the number of partitions to search (probe)
195
+ *
196
+ * This argument is only used when the vector column has an IVF PQ index.
197
+ * If there is no index then this value is ignored.
198
+ *
199
+ * The IVF stage of IVF PQ divides the input into partitions (clusters) of
200
+ * related values.
201
+ *
202
+ * The partition whose centroids are closest to the query vector will be
203
+ * exhaustiely searched to find matches. This parameter controls how many
204
+ * partitions should be searched.
205
+ *
206
+ * Increasing this value will increase the recall of your query but will
207
+ * also increase the latency of your query. The default value is 20. This
208
+ * default is good for many cases but the best value to use will depend on
209
+ * your data and the recall that you need to achieve.
210
+ *
211
+ * For best results we recommend tuning this parameter with a benchmark against
212
+ * your actual data to find the smallest possible value that will still give
213
+ * you the desired recall.
214
+ */
215
+ nprobes(nprobes: number): VectorQuery {
216
+ this.inner.nprobes(nprobes);
217
+ return this;
218
+ }
219
+
220
+ /**
221
+ * Set the vector column to query
222
+ *
223
+ * This controls which column is compared to the query vector supplied in
224
+ * the call to @see {@link Query#nearestTo}
225
+ *
226
+ * This parameter must be specified if the table has more than one column
227
+ * whose data type is a fixed-size-list of floats.
228
+ */
229
+ column(column: string): VectorQuery {
230
+ this.inner.column(column);
231
+ return this;
232
+ }
233
+
234
+ /**
235
+ * Set the distance metric to use
236
+ *
237
+ * When performing a vector search we try and find the "nearest" vectors according
238
+ * to some kind of distance metric. This parameter controls which distance metric to
239
+ * use. See @see {@link IvfPqOptions.distanceType} for more details on the different
240
+ * distance metrics available.
241
+ *
242
+ * Note: if there is a vector index then the distance type used MUST match the distance
243
+ * type used to train the vector index. If this is not done then the results will be
244
+ * invalid.
245
+ *
246
+ * By default "l2" is used.
247
+ */
248
+ distanceType(distanceType: string): VectorQuery {
249
+ this.inner.distanceType(distanceType);
250
+ return this;
251
+ }
252
+
253
+ /**
254
+ * A multiplier to control how many additional rows are taken during the refine step
255
+ *
256
+ * This argument is only used when the vector column has an IVF PQ index.
257
+ * If there is no index then this value is ignored.
258
+ *
259
+ * An IVF PQ index stores compressed (quantized) values. They query vector is compared
260
+ * against these values and, since they are compressed, the comparison is inaccurate.
261
+ *
262
+ * This parameter can be used to refine the results. It can improve both improve recall
263
+ * and correct the ordering of the nearest results.
264
+ *
265
+ * To refine results LanceDb will first perform an ANN search to find the nearest
266
+ * `limit` * `refine_factor` results. In other words, if `refine_factor` is 3 and
267
+ * `limit` is the default (10) then the first 30 results will be selected. LanceDb
268
+ * then fetches the full, uncompressed, values for these 30 results. The results are
269
+ * then reordered by the true distance and only the nearest 10 are kept.
270
+ *
271
+ * Note: there is a difference between calling this method with a value of 1 and never
272
+ * calling this method at all. Calling this method with any value will have an impact
273
+ * on your search latency. When you call this method with a `refine_factor` of 1 then
274
+ * LanceDb still needs to fetch the full, uncompressed, values so that it can potentially
275
+ * reorder the results.
276
+ *
277
+ * Note: if this method is NOT called then the distances returned in the _distance column
278
+ * will be approximate distances based on the comparison of the quantized query vector
279
+ * and the quantized result vectors. This can be considerably different than the true
280
+ * distance between the query vector and the actual uncompressed vector.
281
+ */
282
+ refineFactor(refineFactor: number): VectorQuery {
283
+ this.inner.refineFactor(refineFactor);
284
+ return this;
285
+ }
286
+
287
+ /**
288
+ * If this is called then filtering will happen after the vector search instead of
289
+ * before.
290
+ *
291
+ * By default filtering will be performed before the vector search. This is how
292
+ * filtering is typically understood to work. This prefilter step does add some
293
+ * additional latency. Creating a scalar index on the filter column(s) can
294
+ * often improve this latency. However, sometimes a filter is too complex or scalar
295
+ * indices cannot be applied to the column. In these cases postfiltering can be
296
+ * used instead of prefiltering to improve latency.
297
+ *
298
+ * Post filtering applies the filter to the results of the vector search. This means
299
+ * we only run the filter on a much smaller set of data. However, it can cause the
300
+ * query to return fewer than `limit` results (or even no results) if none of the nearest
301
+ * results match the filter.
302
+ *
303
+ * Post filtering happens during the "refine stage" (described in more detail in
304
+ * @see {@link VectorQuery#refineFactor}). This means that setting a higher refine
305
+ * factor can often help restore some of the results lost by post filtering.
306
+ */
307
+ postfilter(): VectorQuery {
308
+ this.inner.postfilter();
309
+ return this;
310
+ }
311
+
312
+ /**
313
+ * If this is called then any vector index is skipped
314
+ *
315
+ * An exhaustive (flat) search will be performed. The query vector will
316
+ * be compared to every vector in the table. At high scales this can be
317
+ * expensive. However, this is often still useful. For example, skipping
318
+ * the vector index can give you ground truth results which you can use to
319
+ * calculate your recall to select an appropriate value for nprobes.
320
+ */
321
+ bypassVectorIndex(): VectorQuery {
322
+ this.inner.bypassVectorIndex();
323
+ return this;
324
+ }
325
+ }
326
+
327
+ /** A builder for LanceDB queries. */
328
+ export class Query extends QueryBase<NativeQuery, Query> {
329
+ constructor(tbl: NativeTable) {
330
+ super(tbl.query());
331
+ }
332
+
333
+ /**
334
+ * Find the nearest vectors to the given query vector.
335
+ *
336
+ * This converts the query from a plain query to a vector query.
337
+ *
338
+ * This method will attempt to convert the input to the query vector
339
+ * expected by the embedding model. If the input cannot be converted
340
+ * then an error will be thrown.
341
+ *
342
+ * By default, there is no embedding model, and the input should be
343
+ * an array-like object of numbers (something that can be used as input
344
+ * to Float32Array.from)
345
+ *
346
+ * If there is only one vector column (a column whose data type is a
347
+ * fixed size list of floats) then the column does not need to be specified.
348
+ * If there is more than one vector column you must use
349
+ * @see {@link VectorQuery#column} to specify which column you would like
350
+ * to compare with.
351
+ *
352
+ * If no index has been created on the vector column then a vector query
353
+ * will perform a distance comparison between the query vector and every
354
+ * vector in the database and then sort the results. This is sometimes
355
+ * called a "flat search"
356
+ *
357
+ * For small databases, with a few hundred thousand vectors or less, this can
358
+ * be reasonably fast. In larger databases you should create a vector index
359
+ * on the column. If there is a vector index then an "approximate" nearest
360
+ * neighbor search (frequently called an ANN search) will be performed. This
361
+ * search is much faster, but the results will be approximate.
362
+ *
363
+ * The query can be further parameterized using the returned builder. There
364
+ * are various ANN search parameters that will let you fine tune your recall
365
+ * accuracy vs search latency.
366
+ *
367
+ * Vector searches always have a `limit`. If `limit` has not been called then
368
+ * a default `limit` of 10 will be used. @see {@link Query#limit}
369
+ */
370
+ nearestTo(vector: unknown): VectorQuery {
371
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
372
+ const vectorQuery = this.inner.nearestTo(Float32Array.from(vector as any));
373
+ return new VectorQuery(vectorQuery);
374
+ }
375
+ }