@lancedb/lancedb 0.4.3 → 0.4.13
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.
- package/dist/arrow.d.ts +189 -0
- package/dist/arrow.js +539 -0
- package/dist/connection.d.ts +97 -0
- package/dist/connection.js +126 -0
- package/dist/embedding/embedding_function.d.ts +45 -0
- package/dist/embedding/embedding_function.js +27 -0
- package/dist/embedding/index.d.ts +2 -0
- package/dist/embedding/index.js +7 -0
- package/dist/embedding/openai.d.ts +8 -0
- package/dist/embedding/openai.js +53 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +52 -0
- package/dist/indices.d.ts +165 -0
- package/dist/indices.js +71 -0
- package/dist/native.d.ts +147 -0
- package/dist/native.js +314 -0
- package/dist/query.d.ts +248 -0
- package/dist/query.js +346 -0
- package/dist/sanitize.d.ts +9 -0
- package/dist/sanitize.js +369 -0
- package/dist/table.d.ts +252 -0
- package/dist/table.js +298 -0
- package/nodejs-artifacts/arrow.d.ts +189 -0
- package/nodejs-artifacts/arrow.js +539 -0
- package/nodejs-artifacts/connection.d.ts +97 -0
- package/nodejs-artifacts/connection.js +126 -0
- package/nodejs-artifacts/embedding/embedding_function.d.ts +45 -0
- package/nodejs-artifacts/embedding/embedding_function.js +27 -0
- package/nodejs-artifacts/embedding/index.d.ts +2 -0
- package/nodejs-artifacts/embedding/index.js +7 -0
- package/nodejs-artifacts/embedding/openai.d.ts +8 -0
- package/nodejs-artifacts/embedding/openai.js +53 -0
- package/nodejs-artifacts/index.d.ts +22 -0
- package/nodejs-artifacts/index.js +52 -0
- package/nodejs-artifacts/indices.d.ts +165 -0
- package/nodejs-artifacts/indices.js +71 -0
- package/nodejs-artifacts/native.d.ts +147 -0
- package/nodejs-artifacts/native.js +314 -0
- package/nodejs-artifacts/query.d.ts +248 -0
- package/nodejs-artifacts/query.js +346 -0
- package/nodejs-artifacts/sanitize.d.ts +9 -0
- package/nodejs-artifacts/sanitize.js +369 -0
- package/nodejs-artifacts/table.d.ts +252 -0
- package/nodejs-artifacts/table.js +298 -0
- package/package.json +8 -10
- package/examples/js/index.mjs +0 -40
- package/examples/js/package.json +0 -14
- package/examples/js-openai/index.mjs +0 -43
- package/examples/js-openai/package-lock.json +0 -256
- package/examples/js-openai/package.json +0 -15
- package/examples/js-transformers/index.mjs +0 -65
- package/examples/js-transformers/package-lock.json +0 -1418
- package/examples/js-transformers/package.json +0 -15
- package/examples/js-youtube-transcripts/index.mjs +0 -135
- package/examples/js-youtube-transcripts/package.json +0 -15
- package/examples/ts/data/sample-lancedb/vectors.lance/_latest.manifest +0 -0
- package/examples/ts/data/sample-lancedb/vectors.lance/_transactions/0-adde4e05-fcfc-415c-86a6-5b252cb9e79a.txn +0 -0
- package/examples/ts/data/sample-lancedb/vectors.lance/_versions/1.manifest +0 -0
- package/examples/ts/data/sample-lancedb/vectors.lance/data/3618b33e-3eea-4b5e-a0fc-7d1f718d551e.lance +0 -0
- package/examples/ts/package-lock.json +0 -1340
- package/examples/ts/package.json +0 -22
- package/examples/ts/tsconfig.json +0 -10
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Copyright 2023 Lance Developers.
|
|
3
|
+
//
|
|
4
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
// you may not use this file except in compliance with the License.
|
|
6
|
+
// You may obtain a copy of the License at
|
|
7
|
+
//
|
|
8
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
//
|
|
10
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
// See the License for the specific language governing permissions and
|
|
14
|
+
// limitations under the License.
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.createEmptyTable = exports.fromTableToStreamBuffer = exports.fromDataToBuffer = exports.fromTableToBuffer = exports.fromRecordsToStreamBuffer = exports.fromRecordsToBuffer = exports.convertToTable = exports.makeEmptyTable = exports.makeArrowTable = exports.MakeArrowTableOptions = exports.VectorColumnOptions = void 0;
|
|
17
|
+
const apache_arrow_1 = require("apache-arrow");
|
|
18
|
+
const sanitize_1 = require("./sanitize");
|
|
19
|
+
/*
|
|
20
|
+
* Options to control how a column should be converted to a vector array
|
|
21
|
+
*/
|
|
22
|
+
class VectorColumnOptions {
|
|
23
|
+
/** Vector column type. */
|
|
24
|
+
type = new apache_arrow_1.Float32();
|
|
25
|
+
constructor(values) {
|
|
26
|
+
Object.assign(this, values);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
exports.VectorColumnOptions = VectorColumnOptions;
|
|
30
|
+
/** Options to control the makeArrowTable call. */
|
|
31
|
+
class MakeArrowTableOptions {
|
|
32
|
+
/*
|
|
33
|
+
* Schema of the data.
|
|
34
|
+
*
|
|
35
|
+
* If this is not provided then the data type will be inferred from the
|
|
36
|
+
* JS type. Integer numbers will become int64, floating point numbers
|
|
37
|
+
* will become float64 and arrays will become variable sized lists with
|
|
38
|
+
* the data type inferred from the first element in the array.
|
|
39
|
+
*
|
|
40
|
+
* The schema must be specified if there are no records (e.g. to make
|
|
41
|
+
* an empty table)
|
|
42
|
+
*/
|
|
43
|
+
schema;
|
|
44
|
+
/*
|
|
45
|
+
* Mapping from vector column name to expected type
|
|
46
|
+
*
|
|
47
|
+
* Lance expects vector columns to be fixed size list arrays (i.e. tensors)
|
|
48
|
+
* However, `makeArrowTable` will not infer this by default (it creates
|
|
49
|
+
* variable size list arrays). This field can be used to indicate that a column
|
|
50
|
+
* should be treated as a vector column and converted to a fixed size list.
|
|
51
|
+
*
|
|
52
|
+
* The keys should be the names of the vector columns. The value specifies the
|
|
53
|
+
* expected data type of the vector columns.
|
|
54
|
+
*
|
|
55
|
+
* If `schema` is provided then this field is ignored.
|
|
56
|
+
*
|
|
57
|
+
* By default, the column named "vector" will be assumed to be a float32
|
|
58
|
+
* vector column.
|
|
59
|
+
*/
|
|
60
|
+
vectorColumns = {
|
|
61
|
+
vector: new VectorColumnOptions(),
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* If true then string columns will be encoded with dictionary encoding
|
|
65
|
+
*
|
|
66
|
+
* Set this to true if your string columns tend to repeat the same values
|
|
67
|
+
* often. For more precise control use the `schema` property to specify the
|
|
68
|
+
* data type for individual columns.
|
|
69
|
+
*
|
|
70
|
+
* If `schema` is provided then this property is ignored.
|
|
71
|
+
*/
|
|
72
|
+
dictionaryEncodeStrings = false;
|
|
73
|
+
constructor(values) {
|
|
74
|
+
Object.assign(this, values);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
exports.MakeArrowTableOptions = MakeArrowTableOptions;
|
|
78
|
+
/**
|
|
79
|
+
* An enhanced version of the {@link makeTable} function from Apache Arrow
|
|
80
|
+
* that supports nested fields and embeddings columns.
|
|
81
|
+
*
|
|
82
|
+
* (typically you do not need to call this function. It will be called automatically
|
|
83
|
+
* when creating a table or adding data to it)
|
|
84
|
+
*
|
|
85
|
+
* This function converts an array of Record<String, any> (row-major JS objects)
|
|
86
|
+
* to an Arrow Table (a columnar structure)
|
|
87
|
+
*
|
|
88
|
+
* Note that it currently does not support nulls.
|
|
89
|
+
*
|
|
90
|
+
* If a schema is provided then it will be used to determine the resulting array
|
|
91
|
+
* types. Fields will also be reordered to fit the order defined by the schema.
|
|
92
|
+
*
|
|
93
|
+
* If a schema is not provided then the types will be inferred and the field order
|
|
94
|
+
* will be controlled by the order of properties in the first record. If a type
|
|
95
|
+
* is inferred it will always be nullable.
|
|
96
|
+
*
|
|
97
|
+
* If the input is empty then a schema must be provided to create an empty table.
|
|
98
|
+
*
|
|
99
|
+
* When a schema is not specified then data types will be inferred. The inference
|
|
100
|
+
* rules are as follows:
|
|
101
|
+
*
|
|
102
|
+
* - boolean => Bool
|
|
103
|
+
* - number => Float64
|
|
104
|
+
* - String => Utf8
|
|
105
|
+
* - Buffer => Binary
|
|
106
|
+
* - Record<String, any> => Struct
|
|
107
|
+
* - Array<any> => List
|
|
108
|
+
* @example
|
|
109
|
+
* import { fromTableToBuffer, makeArrowTable } from "../arrow";
|
|
110
|
+
* import { Field, FixedSizeList, Float16, Float32, Int32, Schema } from "apache-arrow";
|
|
111
|
+
*
|
|
112
|
+
* const schema = new Schema([
|
|
113
|
+
* new Field("a", new Int32()),
|
|
114
|
+
* new Field("b", new Float32()),
|
|
115
|
+
* new Field("c", new FixedSizeList(3, new Field("item", new Float16()))),
|
|
116
|
+
* ]);
|
|
117
|
+
* const table = makeArrowTable([
|
|
118
|
+
* { a: 1, b: 2, c: [1, 2, 3] },
|
|
119
|
+
* { a: 4, b: 5, c: [4, 5, 6] },
|
|
120
|
+
* { a: 7, b: 8, c: [7, 8, 9] },
|
|
121
|
+
* ], { schema });
|
|
122
|
+
* ```
|
|
123
|
+
*
|
|
124
|
+
* By default it assumes that the column named `vector` is a vector column
|
|
125
|
+
* and it will be converted into a fixed size list array of type float32.
|
|
126
|
+
* The `vectorColumns` option can be used to support other vector column
|
|
127
|
+
* names and data types.
|
|
128
|
+
*
|
|
129
|
+
* ```ts
|
|
130
|
+
*
|
|
131
|
+
* const schema = new Schema([
|
|
132
|
+
new Field("a", new Float64()),
|
|
133
|
+
new Field("b", new Float64()),
|
|
134
|
+
new Field(
|
|
135
|
+
"vector",
|
|
136
|
+
new FixedSizeList(3, new Field("item", new Float32()))
|
|
137
|
+
),
|
|
138
|
+
]);
|
|
139
|
+
const table = makeArrowTable([
|
|
140
|
+
{ a: 1, b: 2, vector: [1, 2, 3] },
|
|
141
|
+
{ a: 4, b: 5, vector: [4, 5, 6] },
|
|
142
|
+
{ a: 7, b: 8, vector: [7, 8, 9] },
|
|
143
|
+
]);
|
|
144
|
+
assert.deepEqual(table.schema, schema);
|
|
145
|
+
* ```
|
|
146
|
+
*
|
|
147
|
+
* You can specify the vector column types and names using the options as well
|
|
148
|
+
*
|
|
149
|
+
* ```typescript
|
|
150
|
+
*
|
|
151
|
+
* const schema = new Schema([
|
|
152
|
+
new Field('a', new Float64()),
|
|
153
|
+
new Field('b', new Float64()),
|
|
154
|
+
new Field('vec1', new FixedSizeList(3, new Field('item', new Float16()))),
|
|
155
|
+
new Field('vec2', new FixedSizeList(3, new Field('item', new Float16())))
|
|
156
|
+
]);
|
|
157
|
+
* const table = makeArrowTable([
|
|
158
|
+
{ a: 1, b: 2, vec1: [1, 2, 3], vec2: [2, 4, 6] },
|
|
159
|
+
{ a: 4, b: 5, vec1: [4, 5, 6], vec2: [8, 10, 12] },
|
|
160
|
+
{ a: 7, b: 8, vec1: [7, 8, 9], vec2: [14, 16, 18] }
|
|
161
|
+
], {
|
|
162
|
+
vectorColumns: {
|
|
163
|
+
vec1: { type: new Float16() },
|
|
164
|
+
vec2: { type: new Float16() }
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
* assert.deepEqual(table.schema, schema)
|
|
168
|
+
* ```
|
|
169
|
+
*/
|
|
170
|
+
function makeArrowTable(data, options) {
|
|
171
|
+
if (data.length === 0 &&
|
|
172
|
+
(options?.schema === undefined || options?.schema === null)) {
|
|
173
|
+
throw new Error("At least one record or a schema needs to be provided");
|
|
174
|
+
}
|
|
175
|
+
const opt = new MakeArrowTableOptions(options !== undefined ? options : {});
|
|
176
|
+
if (opt.schema !== undefined && opt.schema !== null) {
|
|
177
|
+
opt.schema = (0, sanitize_1.sanitizeSchema)(opt.schema);
|
|
178
|
+
}
|
|
179
|
+
const columns = {};
|
|
180
|
+
// TODO: sample dataset to find missing columns
|
|
181
|
+
// Prefer the field ordering of the schema, if present
|
|
182
|
+
const columnNames = opt.schema != null ? opt.schema.names : Object.keys(data[0]);
|
|
183
|
+
for (const colName of columnNames) {
|
|
184
|
+
if (data.length !== 0 &&
|
|
185
|
+
!Object.prototype.hasOwnProperty.call(data[0], colName)) {
|
|
186
|
+
// The field is present in the schema, but not in the data, skip it
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
// Extract a single column from the records (transpose from row-major to col-major)
|
|
190
|
+
let values = data.map((datum) => datum[colName]);
|
|
191
|
+
// By default (type === undefined) arrow will infer the type from the JS type
|
|
192
|
+
let type;
|
|
193
|
+
if (opt.schema !== undefined) {
|
|
194
|
+
// If there is a schema provided, then use that for the type instead
|
|
195
|
+
type = opt.schema?.fields.filter((f) => f.name === colName)[0]?.type;
|
|
196
|
+
if (apache_arrow_1.DataType.isInt(type) && type.bitWidth === 64) {
|
|
197
|
+
// wrap in BigInt to avoid bug: https://github.com/apache/arrow/issues/40051
|
|
198
|
+
values = values.map((v) => {
|
|
199
|
+
if (v === null) {
|
|
200
|
+
return v;
|
|
201
|
+
}
|
|
202
|
+
if (typeof v === "bigint") {
|
|
203
|
+
return v;
|
|
204
|
+
}
|
|
205
|
+
if (typeof v === "number") {
|
|
206
|
+
return BigInt(v);
|
|
207
|
+
}
|
|
208
|
+
throw new Error(`Expected BigInt or number for column ${colName}, got ${typeof v}`);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
// Otherwise, check to see if this column is one of the vector columns
|
|
214
|
+
// defined by opt.vectorColumns and, if so, use the fixed size list type
|
|
215
|
+
const vectorColumnOptions = opt.vectorColumns[colName];
|
|
216
|
+
if (vectorColumnOptions !== undefined) {
|
|
217
|
+
const firstNonNullValue = values.find((v) => v !== null);
|
|
218
|
+
if (Array.isArray(firstNonNullValue)) {
|
|
219
|
+
type = newVectorType(firstNonNullValue.length, vectorColumnOptions.type);
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
throw new Error(`Column ${colName} is expected to be a vector column but first non-null value is not an array. Could not determine size of vector column`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
// Convert an Array of JS values to an arrow vector
|
|
228
|
+
columns[colName] = makeVector(values, type, opt.dictionaryEncodeStrings);
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
232
|
+
throw Error(`Could not convert column "${colName}" to Arrow: ${error}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (opt.schema != null) {
|
|
236
|
+
// `new ArrowTable(columns)` infers a schema which may sometimes have
|
|
237
|
+
// incorrect nullability (it assumes nullable=true always)
|
|
238
|
+
//
|
|
239
|
+
// `new ArrowTable(schema, columns)` will also fail because it will create a
|
|
240
|
+
// batch with an inferred schema and then complain that the batch schema
|
|
241
|
+
// does not match the provided schema.
|
|
242
|
+
//
|
|
243
|
+
// To work around this we first create a table with the wrong schema and
|
|
244
|
+
// then patch the schema of the batches so we can use
|
|
245
|
+
// `new ArrowTable(schema, batches)` which does not do any schema inference
|
|
246
|
+
const firstTable = new apache_arrow_1.Table(columns);
|
|
247
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
248
|
+
const batchesFixed = firstTable.batches.map((batch) => new apache_arrow_1.RecordBatch(opt.schema, batch.data));
|
|
249
|
+
return new apache_arrow_1.Table(opt.schema, batchesFixed);
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
return new apache_arrow_1.Table(columns);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
exports.makeArrowTable = makeArrowTable;
|
|
256
|
+
/**
|
|
257
|
+
* Create an empty Arrow table with the provided schema
|
|
258
|
+
*/
|
|
259
|
+
function makeEmptyTable(schema) {
|
|
260
|
+
return makeArrowTable([], { schema });
|
|
261
|
+
}
|
|
262
|
+
exports.makeEmptyTable = makeEmptyTable;
|
|
263
|
+
/**
|
|
264
|
+
* Helper function to convert Array<Array<any>> to a variable sized list array
|
|
265
|
+
*/
|
|
266
|
+
// @ts-expect-error (Vector<unknown> is not assignable to Vector<any>)
|
|
267
|
+
function makeListVector(lists) {
|
|
268
|
+
if (lists.length === 0 || lists[0].length === 0) {
|
|
269
|
+
throw Error("Cannot infer list vector from empty array or empty list");
|
|
270
|
+
}
|
|
271
|
+
const sampleList = lists[0];
|
|
272
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
273
|
+
let inferredType;
|
|
274
|
+
try {
|
|
275
|
+
const sampleVector = makeVector(sampleList);
|
|
276
|
+
inferredType = sampleVector.type;
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
280
|
+
throw Error(`Cannot infer list vector. Cannot infer inner type: ${error}`);
|
|
281
|
+
}
|
|
282
|
+
const listBuilder = (0, apache_arrow_1.makeBuilder)({
|
|
283
|
+
type: new apache_arrow_1.List(new apache_arrow_1.Field("item", inferredType, true)),
|
|
284
|
+
});
|
|
285
|
+
for (const list of lists) {
|
|
286
|
+
listBuilder.append(list);
|
|
287
|
+
}
|
|
288
|
+
return listBuilder.finish().toVector();
|
|
289
|
+
}
|
|
290
|
+
/** Helper function to convert an Array of JS values to an Arrow Vector */
|
|
291
|
+
function makeVector(values, type, stringAsDictionary) {
|
|
292
|
+
if (type !== undefined) {
|
|
293
|
+
// No need for inference, let Arrow create it
|
|
294
|
+
return (0, apache_arrow_1.vectorFromArray)(values, type);
|
|
295
|
+
}
|
|
296
|
+
if (values.length === 0) {
|
|
297
|
+
throw Error("makeVector requires at least one value or the type must be specfied");
|
|
298
|
+
}
|
|
299
|
+
const sampleValue = values.find((val) => val !== null && val !== undefined);
|
|
300
|
+
if (sampleValue === undefined) {
|
|
301
|
+
throw Error("makeVector cannot infer the type if all values are null or undefined");
|
|
302
|
+
}
|
|
303
|
+
if (Array.isArray(sampleValue)) {
|
|
304
|
+
// Default Arrow inference doesn't handle list types
|
|
305
|
+
return makeListVector(values);
|
|
306
|
+
}
|
|
307
|
+
else if (Buffer.isBuffer(sampleValue)) {
|
|
308
|
+
// Default Arrow inference doesn't handle Buffer
|
|
309
|
+
return (0, apache_arrow_1.vectorFromArray)(values, new apache_arrow_1.Binary());
|
|
310
|
+
}
|
|
311
|
+
else if (!(stringAsDictionary ?? false) &&
|
|
312
|
+
(typeof sampleValue === "string" || sampleValue instanceof String)) {
|
|
313
|
+
// If the type is string then don't use Arrow's default inference unless dictionaries are requested
|
|
314
|
+
// because it will always use dictionary encoding for strings
|
|
315
|
+
return (0, apache_arrow_1.vectorFromArray)(values, new apache_arrow_1.Utf8());
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
// Convert a JS array of values to an arrow vector
|
|
319
|
+
return (0, apache_arrow_1.vectorFromArray)(values);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/** Helper function to apply embeddings to an input table */
|
|
323
|
+
async function applyEmbeddings(table, embeddings, schema) {
|
|
324
|
+
if (embeddings == null) {
|
|
325
|
+
return table;
|
|
326
|
+
}
|
|
327
|
+
if (schema !== undefined && schema !== null) {
|
|
328
|
+
schema = (0, sanitize_1.sanitizeSchema)(schema);
|
|
329
|
+
}
|
|
330
|
+
// Convert from ArrowTable to Record<String, Vector>
|
|
331
|
+
const colEntries = [...Array(table.numCols).keys()].map((_, idx) => {
|
|
332
|
+
const name = table.schema.fields[idx].name;
|
|
333
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
334
|
+
const vec = table.getChildAt(idx);
|
|
335
|
+
return [name, vec];
|
|
336
|
+
});
|
|
337
|
+
const newColumns = Object.fromEntries(colEntries);
|
|
338
|
+
const sourceColumn = newColumns[embeddings.sourceColumn];
|
|
339
|
+
const destColumn = embeddings.destColumn ?? "vector";
|
|
340
|
+
const innerDestType = embeddings.embeddingDataType ?? new apache_arrow_1.Float32();
|
|
341
|
+
if (sourceColumn === undefined) {
|
|
342
|
+
throw new Error(`Cannot apply embedding function because the source column '${embeddings.sourceColumn}' was not present in the data`);
|
|
343
|
+
}
|
|
344
|
+
if (table.numRows === 0) {
|
|
345
|
+
if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
|
|
346
|
+
// We have an empty table and it already has the embedding column so no work needs to be done
|
|
347
|
+
// Note: we don't return an error like we did below because this is a common occurrence. For example,
|
|
348
|
+
// if we call convertToTable with 0 records and a schema that includes the embedding
|
|
349
|
+
return table;
|
|
350
|
+
}
|
|
351
|
+
if (embeddings.embeddingDimension !== undefined) {
|
|
352
|
+
const destType = newVectorType(embeddings.embeddingDimension, innerDestType);
|
|
353
|
+
newColumns[destColumn] = makeVector([], destType);
|
|
354
|
+
}
|
|
355
|
+
else if (schema != null) {
|
|
356
|
+
const destField = schema.fields.find((f) => f.name === destColumn);
|
|
357
|
+
if (destField != null) {
|
|
358
|
+
newColumns[destColumn] = makeVector([], destField.type);
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
throw new Error(`Attempt to apply embeddings to an empty table failed because schema was missing embedding column '${destColumn}'`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
throw new Error("Attempt to apply embeddings to an empty table when the embeddings function does not specify `embeddingDimension`");
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
|
|
370
|
+
throw new Error(`Attempt to apply embeddings to table failed because column ${destColumn} already existed`);
|
|
371
|
+
}
|
|
372
|
+
if (table.batches.length > 1) {
|
|
373
|
+
throw new Error("Internal error: `makeArrowTable` unexpectedly created a table with more than one batch");
|
|
374
|
+
}
|
|
375
|
+
const values = sourceColumn.toArray();
|
|
376
|
+
const vectors = await embeddings.embed(values);
|
|
377
|
+
if (vectors.length !== values.length) {
|
|
378
|
+
throw new Error("Embedding function did not return an embedding for each input element");
|
|
379
|
+
}
|
|
380
|
+
const destType = newVectorType(vectors[0].length, innerDestType);
|
|
381
|
+
newColumns[destColumn] = makeVector(vectors, destType);
|
|
382
|
+
}
|
|
383
|
+
const newTable = new apache_arrow_1.Table(newColumns);
|
|
384
|
+
if (schema != null) {
|
|
385
|
+
if (schema.fields.find((f) => f.name === destColumn) === undefined) {
|
|
386
|
+
throw new Error(`When using embedding functions and specifying a schema the schema should include the embedding column but the column ${destColumn} was missing`);
|
|
387
|
+
}
|
|
388
|
+
return alignTable(newTable, schema);
|
|
389
|
+
}
|
|
390
|
+
return newTable;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Convert an Array of records into an Arrow Table, optionally applying an
|
|
394
|
+
* embeddings function to it.
|
|
395
|
+
*
|
|
396
|
+
* This function calls `makeArrowTable` first to create the Arrow Table.
|
|
397
|
+
* Any provided `makeTableOptions` (e.g. a schema) will be passed on to
|
|
398
|
+
* that call.
|
|
399
|
+
*
|
|
400
|
+
* The embedding function will be passed a column of values (based on the
|
|
401
|
+
* `sourceColumn` of the embedding function) and expects to receive back
|
|
402
|
+
* number[][] which will be converted into a fixed size list column. By
|
|
403
|
+
* default this will be a fixed size list of Float32 but that can be
|
|
404
|
+
* customized by the `embeddingDataType` property of the embedding function.
|
|
405
|
+
*
|
|
406
|
+
* If a schema is provided in `makeTableOptions` then it should include the
|
|
407
|
+
* embedding columns. If no schema is provded then embedding columns will
|
|
408
|
+
* be placed at the end of the table, after all of the input columns.
|
|
409
|
+
*/
|
|
410
|
+
async function convertToTable(data, embeddings, makeTableOptions) {
|
|
411
|
+
const table = makeArrowTable(data, makeTableOptions);
|
|
412
|
+
return await applyEmbeddings(table, embeddings, makeTableOptions?.schema);
|
|
413
|
+
}
|
|
414
|
+
exports.convertToTable = convertToTable;
|
|
415
|
+
/** Creates the Arrow Type for a Vector column with dimension `dim` */
|
|
416
|
+
function newVectorType(dim, innerType) {
|
|
417
|
+
// in Lance we always default to have the elements nullable, so we need to set it to true
|
|
418
|
+
// otherwise we often get schema mismatches because the stored data always has schema with nullable elements
|
|
419
|
+
const children = new apache_arrow_1.Field("item", innerType, true);
|
|
420
|
+
return new apache_arrow_1.FixedSizeList(dim, children);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Serialize an Array of records into a buffer using the Arrow IPC File serialization
|
|
424
|
+
*
|
|
425
|
+
* This function will call `convertToTable` and pass on `embeddings` and `schema`
|
|
426
|
+
*
|
|
427
|
+
* `schema` is required if data is empty
|
|
428
|
+
*/
|
|
429
|
+
async function fromRecordsToBuffer(data, embeddings, schema) {
|
|
430
|
+
if (schema !== undefined && schema !== null) {
|
|
431
|
+
schema = (0, sanitize_1.sanitizeSchema)(schema);
|
|
432
|
+
}
|
|
433
|
+
const table = await convertToTable(data, embeddings, { schema });
|
|
434
|
+
const writer = apache_arrow_1.RecordBatchFileWriter.writeAll(table);
|
|
435
|
+
return Buffer.from(await writer.toUint8Array());
|
|
436
|
+
}
|
|
437
|
+
exports.fromRecordsToBuffer = fromRecordsToBuffer;
|
|
438
|
+
/**
|
|
439
|
+
* Serialize an Array of records into a buffer using the Arrow IPC Stream serialization
|
|
440
|
+
*
|
|
441
|
+
* This function will call `convertToTable` and pass on `embeddings` and `schema`
|
|
442
|
+
*
|
|
443
|
+
* `schema` is required if data is empty
|
|
444
|
+
*/
|
|
445
|
+
async function fromRecordsToStreamBuffer(data, embeddings, schema) {
|
|
446
|
+
if (schema !== undefined && schema !== null) {
|
|
447
|
+
schema = (0, sanitize_1.sanitizeSchema)(schema);
|
|
448
|
+
}
|
|
449
|
+
const table = await convertToTable(data, embeddings, { schema });
|
|
450
|
+
const writer = apache_arrow_1.RecordBatchStreamWriter.writeAll(table);
|
|
451
|
+
return Buffer.from(await writer.toUint8Array());
|
|
452
|
+
}
|
|
453
|
+
exports.fromRecordsToStreamBuffer = fromRecordsToStreamBuffer;
|
|
454
|
+
/**
|
|
455
|
+
* Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
|
|
456
|
+
*
|
|
457
|
+
* This function will apply `embeddings` to the table in a manner similar to
|
|
458
|
+
* `convertToTable`.
|
|
459
|
+
*
|
|
460
|
+
* `schema` is required if the table is empty
|
|
461
|
+
*/
|
|
462
|
+
async function fromTableToBuffer(table, embeddings, schema) {
|
|
463
|
+
if (schema !== undefined && schema !== null) {
|
|
464
|
+
schema = (0, sanitize_1.sanitizeSchema)(schema);
|
|
465
|
+
}
|
|
466
|
+
const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
|
|
467
|
+
const writer = apache_arrow_1.RecordBatchFileWriter.writeAll(tableWithEmbeddings);
|
|
468
|
+
return Buffer.from(await writer.toUint8Array());
|
|
469
|
+
}
|
|
470
|
+
exports.fromTableToBuffer = fromTableToBuffer;
|
|
471
|
+
/**
|
|
472
|
+
* Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
|
|
473
|
+
*
|
|
474
|
+
* This function will apply `embeddings` to the table in a manner similar to
|
|
475
|
+
* `convertToTable`.
|
|
476
|
+
*
|
|
477
|
+
* `schema` is required if the table is empty
|
|
478
|
+
*/
|
|
479
|
+
async function fromDataToBuffer(data, embeddings, schema) {
|
|
480
|
+
if (schema !== undefined && schema !== null) {
|
|
481
|
+
schema = (0, sanitize_1.sanitizeSchema)(schema);
|
|
482
|
+
}
|
|
483
|
+
if (data instanceof apache_arrow_1.Table) {
|
|
484
|
+
return fromTableToBuffer(data, embeddings, schema);
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
const table = await convertToTable(data);
|
|
488
|
+
return fromTableToBuffer(table, embeddings, schema);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
exports.fromDataToBuffer = fromDataToBuffer;
|
|
492
|
+
/**
|
|
493
|
+
* Serialize an Arrow Table into a buffer using the Arrow IPC Stream serialization
|
|
494
|
+
*
|
|
495
|
+
* This function will apply `embeddings` to the table in a manner similar to
|
|
496
|
+
* `convertToTable`.
|
|
497
|
+
*
|
|
498
|
+
* `schema` is required if the table is empty
|
|
499
|
+
*/
|
|
500
|
+
async function fromTableToStreamBuffer(table, embeddings, schema) {
|
|
501
|
+
const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
|
|
502
|
+
const writer = apache_arrow_1.RecordBatchStreamWriter.writeAll(tableWithEmbeddings);
|
|
503
|
+
return Buffer.from(await writer.toUint8Array());
|
|
504
|
+
}
|
|
505
|
+
exports.fromTableToStreamBuffer = fromTableToStreamBuffer;
|
|
506
|
+
/**
|
|
507
|
+
* Reorder the columns in `batch` so that they agree with the field order in `schema`
|
|
508
|
+
*/
|
|
509
|
+
function alignBatch(batch, schema) {
|
|
510
|
+
const alignedChildren = [];
|
|
511
|
+
for (const field of schema.fields) {
|
|
512
|
+
const indexInBatch = batch.schema.fields?.findIndex((f) => f.name === field.name);
|
|
513
|
+
if (indexInBatch < 0) {
|
|
514
|
+
throw new Error(`The column ${field.name} was not found in the Arrow Table`);
|
|
515
|
+
}
|
|
516
|
+
alignedChildren.push(batch.data.children[indexInBatch]);
|
|
517
|
+
}
|
|
518
|
+
const newData = (0, apache_arrow_1.makeData)({
|
|
519
|
+
type: new apache_arrow_1.Struct(schema.fields),
|
|
520
|
+
length: batch.numRows,
|
|
521
|
+
nullCount: batch.nullCount,
|
|
522
|
+
children: alignedChildren,
|
|
523
|
+
});
|
|
524
|
+
return new apache_arrow_1.RecordBatch(schema, newData);
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Reorder the columns in `table` so that they agree with the field order in `schema`
|
|
528
|
+
*/
|
|
529
|
+
function alignTable(table, schema) {
|
|
530
|
+
const alignedBatches = table.batches.map((batch) => alignBatch(batch, schema));
|
|
531
|
+
return new apache_arrow_1.Table(schema, alignedBatches);
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Create an empty table with the given schema
|
|
535
|
+
*/
|
|
536
|
+
function createEmptyTable(schema) {
|
|
537
|
+
return new apache_arrow_1.Table((0, sanitize_1.sanitizeSchema)(schema));
|
|
538
|
+
}
|
|
539
|
+
exports.createEmptyTable = createEmptyTable;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { Connection as LanceDbConnection } from "./native";
|
|
2
|
+
import { Table } from "./table";
|
|
3
|
+
import { Table as ArrowTable, Schema } from "apache-arrow";
|
|
4
|
+
export interface CreateTableOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The mode to use when creating the table.
|
|
7
|
+
*
|
|
8
|
+
* If this is set to "create" and the table already exists then either
|
|
9
|
+
* an error will be thrown or, if existOk is true, then nothing will
|
|
10
|
+
* happen. Any provided data will be ignored.
|
|
11
|
+
*
|
|
12
|
+
* If this is set to "overwrite" then any existing table will be replaced.
|
|
13
|
+
*/
|
|
14
|
+
mode: "create" | "overwrite";
|
|
15
|
+
/**
|
|
16
|
+
* If this is true and the table already exists and the mode is "create"
|
|
17
|
+
* then no error will be raised.
|
|
18
|
+
*/
|
|
19
|
+
existOk: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface TableNamesOptions {
|
|
22
|
+
/**
|
|
23
|
+
* If present, only return names that come lexicographically after the
|
|
24
|
+
* supplied value.
|
|
25
|
+
*
|
|
26
|
+
* This can be combined with limit to implement pagination by setting this to
|
|
27
|
+
* the last table name from the previous page.
|
|
28
|
+
*/
|
|
29
|
+
startAfter?: string;
|
|
30
|
+
/** An optional limit to the number of results to return. */
|
|
31
|
+
limit?: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A LanceDB Connection that allows you to open tables and create new ones.
|
|
35
|
+
*
|
|
36
|
+
* Connection could be local against filesystem or remote against a server.
|
|
37
|
+
*
|
|
38
|
+
* A Connection is intended to be a long lived object and may hold open
|
|
39
|
+
* resources such as HTTP connection pools. This is generally fine and
|
|
40
|
+
* a single connection should be shared if it is going to be used many
|
|
41
|
+
* times. However, if you are finished with a connection, you may call
|
|
42
|
+
* close to eagerly free these resources. Any call to a Connection
|
|
43
|
+
* method after it has been closed will result in an error.
|
|
44
|
+
*
|
|
45
|
+
* Closing a connection is optional. Connections will automatically
|
|
46
|
+
* be closed when they are garbage collected.
|
|
47
|
+
*
|
|
48
|
+
* Any created tables are independent and will continue to work even if
|
|
49
|
+
* the underlying connection has been closed.
|
|
50
|
+
*/
|
|
51
|
+
export declare class Connection {
|
|
52
|
+
readonly inner: LanceDbConnection;
|
|
53
|
+
constructor(inner: LanceDbConnection);
|
|
54
|
+
/** Return true if the connection has not been closed */
|
|
55
|
+
isOpen(): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Close the connection, releasing any underlying resources.
|
|
58
|
+
*
|
|
59
|
+
* It is safe to call this method multiple times.
|
|
60
|
+
*
|
|
61
|
+
* Any attempt to use the connection after it is closed will result in an error.
|
|
62
|
+
*/
|
|
63
|
+
close(): void;
|
|
64
|
+
/** Return a brief description of the connection */
|
|
65
|
+
display(): string;
|
|
66
|
+
/**
|
|
67
|
+
* List all the table names in this database.
|
|
68
|
+
*
|
|
69
|
+
* Tables will be returned in lexicographical order.
|
|
70
|
+
* @param {Partial<TableNamesOptions>} options - options to control the
|
|
71
|
+
* paging / start point
|
|
72
|
+
*/
|
|
73
|
+
tableNames(options?: Partial<TableNamesOptions>): Promise<string[]>;
|
|
74
|
+
/**
|
|
75
|
+
* Open a table in the database.
|
|
76
|
+
* @param {string} name - The name of the table
|
|
77
|
+
*/
|
|
78
|
+
openTable(name: string): Promise<Table>;
|
|
79
|
+
/**
|
|
80
|
+
* Creates a new Table and initialize it with new data.
|
|
81
|
+
* @param {string} name - The name of the table.
|
|
82
|
+
* @param {Record<string, unknown>[] | ArrowTable} data - Non-empty Array of Records
|
|
83
|
+
* to be inserted into the table
|
|
84
|
+
*/
|
|
85
|
+
createTable(name: string, data: Record<string, unknown>[] | ArrowTable, options?: Partial<CreateTableOptions>): Promise<Table>;
|
|
86
|
+
/**
|
|
87
|
+
* Creates a new empty Table
|
|
88
|
+
* @param {string} name - The name of the table.
|
|
89
|
+
* @param {Schema} schema - The schema of the table
|
|
90
|
+
*/
|
|
91
|
+
createEmptyTable(name: string, schema: Schema, options?: Partial<CreateTableOptions>): Promise<Table>;
|
|
92
|
+
/**
|
|
93
|
+
* Drop an existing table.
|
|
94
|
+
* @param {string} name The name of the table to drop.
|
|
95
|
+
*/
|
|
96
|
+
dropTable(name: string): Promise<void>;
|
|
97
|
+
}
|