@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,22 @@
1
+ {
2
+ "name": "vectordb-example-ts",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "tsc": "tsc -b",
9
+ "build": "tsc"
10
+ },
11
+ "author": "Lance Devs",
12
+ "license": "Apache-2.0",
13
+ "devDependencies": {
14
+ "@types/node": "^18.16.2",
15
+ "ts-node": "^10.9.1",
16
+ "ts-node-dev": "^2.0.0",
17
+ "typescript": "*"
18
+ },
19
+ "dependencies": {
20
+ "@lancedb/lancedb": "file:../.."
21
+ }
22
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "include": ["src/**/*.ts"],
3
+ "compilerOptions": {
4
+ "target": "es2016",
5
+ "module": "commonjs",
6
+ "declaration": true,
7
+ "outDir": "./dist",
8
+ "strict": true
9
+ }
10
+ }
package/jest.config.js ADDED
@@ -0,0 +1,7 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: "ts-jest",
4
+ testEnvironment: "node",
5
+ moduleDirectories: ["node_modules", "./dist"],
6
+ moduleFileExtensions: ["js", "ts"],
7
+ };
@@ -0,0 +1,650 @@
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 {
16
+ Field,
17
+ makeBuilder,
18
+ RecordBatchFileWriter,
19
+ Utf8,
20
+ type Vector,
21
+ FixedSizeList,
22
+ vectorFromArray,
23
+ type Schema,
24
+ Table as ArrowTable,
25
+ RecordBatchStreamWriter,
26
+ List,
27
+ RecordBatch,
28
+ makeData,
29
+ Struct,
30
+ type Float,
31
+ DataType,
32
+ Binary,
33
+ Float32,
34
+ type makeTable,
35
+ } from "apache-arrow";
36
+ import { type EmbeddingFunction } from "./embedding/embedding_function";
37
+ import { sanitizeSchema } from "./sanitize";
38
+
39
+ /** Data type accepted by NodeJS SDK */
40
+ export type Data = Record<string, unknown>[] | ArrowTable;
41
+
42
+ /*
43
+ * Options to control how a column should be converted to a vector array
44
+ */
45
+ export class VectorColumnOptions {
46
+ /** Vector column type. */
47
+ type: Float = new Float32();
48
+
49
+ constructor(values?: Partial<VectorColumnOptions>) {
50
+ Object.assign(this, values);
51
+ }
52
+ }
53
+
54
+ /** Options to control the makeArrowTable call. */
55
+ export class MakeArrowTableOptions {
56
+ /*
57
+ * Schema of the data.
58
+ *
59
+ * If this is not provided then the data type will be inferred from the
60
+ * JS type. Integer numbers will become int64, floating point numbers
61
+ * will become float64 and arrays will become variable sized lists with
62
+ * the data type inferred from the first element in the array.
63
+ *
64
+ * The schema must be specified if there are no records (e.g. to make
65
+ * an empty table)
66
+ */
67
+ schema?: Schema;
68
+
69
+ /*
70
+ * Mapping from vector column name to expected type
71
+ *
72
+ * Lance expects vector columns to be fixed size list arrays (i.e. tensors)
73
+ * However, `makeArrowTable` will not infer this by default (it creates
74
+ * variable size list arrays). This field can be used to indicate that a column
75
+ * should be treated as a vector column and converted to a fixed size list.
76
+ *
77
+ * The keys should be the names of the vector columns. The value specifies the
78
+ * expected data type of the vector columns.
79
+ *
80
+ * If `schema` is provided then this field is ignored.
81
+ *
82
+ * By default, the column named "vector" will be assumed to be a float32
83
+ * vector column.
84
+ */
85
+ vectorColumns: Record<string, VectorColumnOptions> = {
86
+ vector: new VectorColumnOptions(),
87
+ };
88
+
89
+ /**
90
+ * If true then string columns will be encoded with dictionary encoding
91
+ *
92
+ * Set this to true if your string columns tend to repeat the same values
93
+ * often. For more precise control use the `schema` property to specify the
94
+ * data type for individual columns.
95
+ *
96
+ * If `schema` is provided then this property is ignored.
97
+ */
98
+ dictionaryEncodeStrings: boolean = false;
99
+
100
+ constructor(values?: Partial<MakeArrowTableOptions>) {
101
+ Object.assign(this, values);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * An enhanced version of the {@link makeTable} function from Apache Arrow
107
+ * that supports nested fields and embeddings columns.
108
+ *
109
+ * (typically you do not need to call this function. It will be called automatically
110
+ * when creating a table or adding data to it)
111
+ *
112
+ * This function converts an array of Record<String, any> (row-major JS objects)
113
+ * to an Arrow Table (a columnar structure)
114
+ *
115
+ * Note that it currently does not support nulls.
116
+ *
117
+ * If a schema is provided then it will be used to determine the resulting array
118
+ * types. Fields will also be reordered to fit the order defined by the schema.
119
+ *
120
+ * If a schema is not provided then the types will be inferred and the field order
121
+ * will be controlled by the order of properties in the first record. If a type
122
+ * is inferred it will always be nullable.
123
+ *
124
+ * If the input is empty then a schema must be provided to create an empty table.
125
+ *
126
+ * When a schema is not specified then data types will be inferred. The inference
127
+ * rules are as follows:
128
+ *
129
+ * - boolean => Bool
130
+ * - number => Float64
131
+ * - String => Utf8
132
+ * - Buffer => Binary
133
+ * - Record<String, any> => Struct
134
+ * - Array<any> => List
135
+ * @example
136
+ * import { fromTableToBuffer, makeArrowTable } from "../arrow";
137
+ * import { Field, FixedSizeList, Float16, Float32, Int32, Schema } from "apache-arrow";
138
+ *
139
+ * const schema = new Schema([
140
+ * new Field("a", new Int32()),
141
+ * new Field("b", new Float32()),
142
+ * new Field("c", new FixedSizeList(3, new Field("item", new Float16()))),
143
+ * ]);
144
+ * const table = makeArrowTable([
145
+ * { a: 1, b: 2, c: [1, 2, 3] },
146
+ * { a: 4, b: 5, c: [4, 5, 6] },
147
+ * { a: 7, b: 8, c: [7, 8, 9] },
148
+ * ], { schema });
149
+ * ```
150
+ *
151
+ * By default it assumes that the column named `vector` is a vector column
152
+ * and it will be converted into a fixed size list array of type float32.
153
+ * The `vectorColumns` option can be used to support other vector column
154
+ * names and data types.
155
+ *
156
+ * ```ts
157
+ *
158
+ * const schema = new Schema([
159
+ new Field("a", new Float64()),
160
+ new Field("b", new Float64()),
161
+ new Field(
162
+ "vector",
163
+ new FixedSizeList(3, new Field("item", new Float32()))
164
+ ),
165
+ ]);
166
+ const table = makeArrowTable([
167
+ { a: 1, b: 2, vector: [1, 2, 3] },
168
+ { a: 4, b: 5, vector: [4, 5, 6] },
169
+ { a: 7, b: 8, vector: [7, 8, 9] },
170
+ ]);
171
+ assert.deepEqual(table.schema, schema);
172
+ * ```
173
+ *
174
+ * You can specify the vector column types and names using the options as well
175
+ *
176
+ * ```typescript
177
+ *
178
+ * const schema = new Schema([
179
+ new Field('a', new Float64()),
180
+ new Field('b', new Float64()),
181
+ new Field('vec1', new FixedSizeList(3, new Field('item', new Float16()))),
182
+ new Field('vec2', new FixedSizeList(3, new Field('item', new Float16())))
183
+ ]);
184
+ * const table = makeArrowTable([
185
+ { a: 1, b: 2, vec1: [1, 2, 3], vec2: [2, 4, 6] },
186
+ { a: 4, b: 5, vec1: [4, 5, 6], vec2: [8, 10, 12] },
187
+ { a: 7, b: 8, vec1: [7, 8, 9], vec2: [14, 16, 18] }
188
+ ], {
189
+ vectorColumns: {
190
+ vec1: { type: new Float16() },
191
+ vec2: { type: new Float16() }
192
+ }
193
+ }
194
+ * assert.deepEqual(table.schema, schema)
195
+ * ```
196
+ */
197
+ export function makeArrowTable(
198
+ data: Array<Record<string, unknown>>,
199
+ options?: Partial<MakeArrowTableOptions>,
200
+ ): ArrowTable {
201
+ if (
202
+ data.length === 0 &&
203
+ (options?.schema === undefined || options?.schema === null)
204
+ ) {
205
+ throw new Error("At least one record or a schema needs to be provided");
206
+ }
207
+
208
+ const opt = new MakeArrowTableOptions(options !== undefined ? options : {});
209
+ if (opt.schema !== undefined && opt.schema !== null) {
210
+ opt.schema = sanitizeSchema(opt.schema);
211
+ }
212
+ const columns: Record<string, Vector> = {};
213
+ // TODO: sample dataset to find missing columns
214
+ // Prefer the field ordering of the schema, if present
215
+ const columnNames =
216
+ opt.schema != null ? (opt.schema.names as string[]) : Object.keys(data[0]);
217
+ for (const colName of columnNames) {
218
+ if (
219
+ data.length !== 0 &&
220
+ !Object.prototype.hasOwnProperty.call(data[0], colName)
221
+ ) {
222
+ // The field is present in the schema, but not in the data, skip it
223
+ continue;
224
+ }
225
+ // Extract a single column from the records (transpose from row-major to col-major)
226
+ let values = data.map((datum) => datum[colName]);
227
+
228
+ // By default (type === undefined) arrow will infer the type from the JS type
229
+ let type;
230
+ if (opt.schema !== undefined) {
231
+ // If there is a schema provided, then use that for the type instead
232
+ type = opt.schema?.fields.filter((f) => f.name === colName)[0]?.type;
233
+ if (DataType.isInt(type) && type.bitWidth === 64) {
234
+ // wrap in BigInt to avoid bug: https://github.com/apache/arrow/issues/40051
235
+ values = values.map((v) => {
236
+ if (v === null) {
237
+ return v;
238
+ }
239
+ if (typeof v === "bigint") {
240
+ return v;
241
+ }
242
+ if (typeof v === "number") {
243
+ return BigInt(v);
244
+ }
245
+ throw new Error(
246
+ `Expected BigInt or number for column ${colName}, got ${typeof v}`,
247
+ );
248
+ });
249
+ }
250
+ } else {
251
+ // Otherwise, check to see if this column is one of the vector columns
252
+ // defined by opt.vectorColumns and, if so, use the fixed size list type
253
+ const vectorColumnOptions = opt.vectorColumns[colName];
254
+ if (vectorColumnOptions !== undefined) {
255
+ const firstNonNullValue = values.find((v) => v !== null);
256
+ if (Array.isArray(firstNonNullValue)) {
257
+ type = newVectorType(
258
+ firstNonNullValue.length,
259
+ vectorColumnOptions.type,
260
+ );
261
+ } else {
262
+ throw new Error(
263
+ `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`,
264
+ );
265
+ }
266
+ }
267
+ }
268
+
269
+ try {
270
+ // Convert an Array of JS values to an arrow vector
271
+ columns[colName] = makeVector(values, type, opt.dictionaryEncodeStrings);
272
+ } catch (error: unknown) {
273
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
274
+ throw Error(`Could not convert column "${colName}" to Arrow: ${error}`);
275
+ }
276
+ }
277
+
278
+ if (opt.schema != null) {
279
+ // `new ArrowTable(columns)` infers a schema which may sometimes have
280
+ // incorrect nullability (it assumes nullable=true always)
281
+ //
282
+ // `new ArrowTable(schema, columns)` will also fail because it will create a
283
+ // batch with an inferred schema and then complain that the batch schema
284
+ // does not match the provided schema.
285
+ //
286
+ // To work around this we first create a table with the wrong schema and
287
+ // then patch the schema of the batches so we can use
288
+ // `new ArrowTable(schema, batches)` which does not do any schema inference
289
+ const firstTable = new ArrowTable(columns);
290
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
291
+ const batchesFixed = firstTable.batches.map(
292
+ (batch) => new RecordBatch(opt.schema!, batch.data),
293
+ );
294
+ return new ArrowTable(opt.schema, batchesFixed);
295
+ } else {
296
+ return new ArrowTable(columns);
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Create an empty Arrow table with the provided schema
302
+ */
303
+ export function makeEmptyTable(schema: Schema): ArrowTable {
304
+ return makeArrowTable([], { schema });
305
+ }
306
+
307
+ /**
308
+ * Helper function to convert Array<Array<any>> to a variable sized list array
309
+ */
310
+ // @ts-expect-error (Vector<unknown> is not assignable to Vector<any>)
311
+ function makeListVector(lists: unknown[][]): Vector<unknown> {
312
+ if (lists.length === 0 || lists[0].length === 0) {
313
+ throw Error("Cannot infer list vector from empty array or empty list");
314
+ }
315
+ const sampleList = lists[0];
316
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
317
+ let inferredType: any;
318
+ try {
319
+ const sampleVector = makeVector(sampleList);
320
+ inferredType = sampleVector.type;
321
+ } catch (error: unknown) {
322
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
323
+ throw Error(`Cannot infer list vector. Cannot infer inner type: ${error}`);
324
+ }
325
+
326
+ const listBuilder = makeBuilder({
327
+ type: new List(new Field("item", inferredType, true)),
328
+ });
329
+ for (const list of lists) {
330
+ listBuilder.append(list);
331
+ }
332
+ return listBuilder.finish().toVector();
333
+ }
334
+
335
+ /** Helper function to convert an Array of JS values to an Arrow Vector */
336
+ function makeVector(
337
+ values: unknown[],
338
+ type?: DataType,
339
+ stringAsDictionary?: boolean,
340
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
341
+ ): Vector<any> {
342
+ if (type !== undefined) {
343
+ // No need for inference, let Arrow create it
344
+ return vectorFromArray(values, type);
345
+ }
346
+ if (values.length === 0) {
347
+ throw Error(
348
+ "makeVector requires at least one value or the type must be specfied",
349
+ );
350
+ }
351
+ const sampleValue = values.find((val) => val !== null && val !== undefined);
352
+ if (sampleValue === undefined) {
353
+ throw Error(
354
+ "makeVector cannot infer the type if all values are null or undefined",
355
+ );
356
+ }
357
+ if (Array.isArray(sampleValue)) {
358
+ // Default Arrow inference doesn't handle list types
359
+ return makeListVector(values as unknown[][]);
360
+ } else if (Buffer.isBuffer(sampleValue)) {
361
+ // Default Arrow inference doesn't handle Buffer
362
+ return vectorFromArray(values, new Binary());
363
+ } else if (
364
+ !(stringAsDictionary ?? false) &&
365
+ (typeof sampleValue === "string" || sampleValue instanceof String)
366
+ ) {
367
+ // If the type is string then don't use Arrow's default inference unless dictionaries are requested
368
+ // because it will always use dictionary encoding for strings
369
+ return vectorFromArray(values, new Utf8());
370
+ } else {
371
+ // Convert a JS array of values to an arrow vector
372
+ return vectorFromArray(values);
373
+ }
374
+ }
375
+
376
+ /** Helper function to apply embeddings to an input table */
377
+ async function applyEmbeddings<T>(
378
+ table: ArrowTable,
379
+ embeddings?: EmbeddingFunction<T>,
380
+ schema?: Schema,
381
+ ): Promise<ArrowTable> {
382
+ if (embeddings == null) {
383
+ return table;
384
+ }
385
+
386
+ if (schema !== undefined && schema !== null) {
387
+ schema = sanitizeSchema(schema);
388
+ }
389
+
390
+ // Convert from ArrowTable to Record<String, Vector>
391
+ const colEntries = [...Array(table.numCols).keys()].map((_, idx) => {
392
+ const name = table.schema.fields[idx].name;
393
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
394
+ const vec = table.getChildAt(idx)!;
395
+ return [name, vec];
396
+ });
397
+ const newColumns = Object.fromEntries(colEntries);
398
+
399
+ const sourceColumn = newColumns[embeddings.sourceColumn];
400
+ const destColumn = embeddings.destColumn ?? "vector";
401
+ const innerDestType = embeddings.embeddingDataType ?? new Float32();
402
+ if (sourceColumn === undefined) {
403
+ throw new Error(
404
+ `Cannot apply embedding function because the source column '${embeddings.sourceColumn}' was not present in the data`,
405
+ );
406
+ }
407
+
408
+ if (table.numRows === 0) {
409
+ if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
410
+ // We have an empty table and it already has the embedding column so no work needs to be done
411
+ // Note: we don't return an error like we did below because this is a common occurrence. For example,
412
+ // if we call convertToTable with 0 records and a schema that includes the embedding
413
+ return table;
414
+ }
415
+ if (embeddings.embeddingDimension !== undefined) {
416
+ const destType = newVectorType(
417
+ embeddings.embeddingDimension,
418
+ innerDestType,
419
+ );
420
+ newColumns[destColumn] = makeVector([], destType);
421
+ } else if (schema != null) {
422
+ const destField = schema.fields.find((f) => f.name === destColumn);
423
+ if (destField != null) {
424
+ newColumns[destColumn] = makeVector([], destField.type);
425
+ } else {
426
+ throw new Error(
427
+ `Attempt to apply embeddings to an empty table failed because schema was missing embedding column '${destColumn}'`,
428
+ );
429
+ }
430
+ } else {
431
+ throw new Error(
432
+ "Attempt to apply embeddings to an empty table when the embeddings function does not specify `embeddingDimension`",
433
+ );
434
+ }
435
+ } else {
436
+ if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
437
+ throw new Error(
438
+ `Attempt to apply embeddings to table failed because column ${destColumn} already existed`,
439
+ );
440
+ }
441
+ if (table.batches.length > 1) {
442
+ throw new Error(
443
+ "Internal error: `makeArrowTable` unexpectedly created a table with more than one batch",
444
+ );
445
+ }
446
+ const values = sourceColumn.toArray();
447
+ const vectors = await embeddings.embed(values as T[]);
448
+ if (vectors.length !== values.length) {
449
+ throw new Error(
450
+ "Embedding function did not return an embedding for each input element",
451
+ );
452
+ }
453
+ const destType = newVectorType(vectors[0].length, innerDestType);
454
+ newColumns[destColumn] = makeVector(vectors, destType);
455
+ }
456
+
457
+ const newTable = new ArrowTable(newColumns);
458
+ if (schema != null) {
459
+ if (schema.fields.find((f) => f.name === destColumn) === undefined) {
460
+ throw new Error(
461
+ `When using embedding functions and specifying a schema the schema should include the embedding column but the column ${destColumn} was missing`,
462
+ );
463
+ }
464
+ return alignTable(newTable, schema);
465
+ }
466
+ return newTable;
467
+ }
468
+
469
+ /**
470
+ * Convert an Array of records into an Arrow Table, optionally applying an
471
+ * embeddings function to it.
472
+ *
473
+ * This function calls `makeArrowTable` first to create the Arrow Table.
474
+ * Any provided `makeTableOptions` (e.g. a schema) will be passed on to
475
+ * that call.
476
+ *
477
+ * The embedding function will be passed a column of values (based on the
478
+ * `sourceColumn` of the embedding function) and expects to receive back
479
+ * number[][] which will be converted into a fixed size list column. By
480
+ * default this will be a fixed size list of Float32 but that can be
481
+ * customized by the `embeddingDataType` property of the embedding function.
482
+ *
483
+ * If a schema is provided in `makeTableOptions` then it should include the
484
+ * embedding columns. If no schema is provded then embedding columns will
485
+ * be placed at the end of the table, after all of the input columns.
486
+ */
487
+ export async function convertToTable<T>(
488
+ data: Array<Record<string, unknown>>,
489
+ embeddings?: EmbeddingFunction<T>,
490
+ makeTableOptions?: Partial<MakeArrowTableOptions>,
491
+ ): Promise<ArrowTable> {
492
+ const table = makeArrowTable(data, makeTableOptions);
493
+ return await applyEmbeddings(table, embeddings, makeTableOptions?.schema);
494
+ }
495
+
496
+ /** Creates the Arrow Type for a Vector column with dimension `dim` */
497
+ function newVectorType<T extends Float>(
498
+ dim: number,
499
+ innerType: T,
500
+ ): FixedSizeList<T> {
501
+ // in Lance we always default to have the elements nullable, so we need to set it to true
502
+ // otherwise we often get schema mismatches because the stored data always has schema with nullable elements
503
+ const children = new Field<T>("item", innerType, true);
504
+ return new FixedSizeList(dim, children);
505
+ }
506
+
507
+ /**
508
+ * Serialize an Array of records into a buffer using the Arrow IPC File serialization
509
+ *
510
+ * This function will call `convertToTable` and pass on `embeddings` and `schema`
511
+ *
512
+ * `schema` is required if data is empty
513
+ */
514
+ export async function fromRecordsToBuffer<T>(
515
+ data: Array<Record<string, unknown>>,
516
+ embeddings?: EmbeddingFunction<T>,
517
+ schema?: Schema,
518
+ ): Promise<Buffer> {
519
+ if (schema !== undefined && schema !== null) {
520
+ schema = sanitizeSchema(schema);
521
+ }
522
+ const table = await convertToTable(data, embeddings, { schema });
523
+ const writer = RecordBatchFileWriter.writeAll(table);
524
+ return Buffer.from(await writer.toUint8Array());
525
+ }
526
+
527
+ /**
528
+ * Serialize an Array of records into a buffer using the Arrow IPC Stream serialization
529
+ *
530
+ * This function will call `convertToTable` and pass on `embeddings` and `schema`
531
+ *
532
+ * `schema` is required if data is empty
533
+ */
534
+ export async function fromRecordsToStreamBuffer<T>(
535
+ data: Array<Record<string, unknown>>,
536
+ embeddings?: EmbeddingFunction<T>,
537
+ schema?: Schema,
538
+ ): Promise<Buffer> {
539
+ if (schema !== undefined && schema !== null) {
540
+ schema = sanitizeSchema(schema);
541
+ }
542
+ const table = await convertToTable(data, embeddings, { schema });
543
+ const writer = RecordBatchStreamWriter.writeAll(table);
544
+ return Buffer.from(await writer.toUint8Array());
545
+ }
546
+
547
+ /**
548
+ * Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
549
+ *
550
+ * This function will apply `embeddings` to the table in a manner similar to
551
+ * `convertToTable`.
552
+ *
553
+ * `schema` is required if the table is empty
554
+ */
555
+ export async function fromTableToBuffer<T>(
556
+ table: ArrowTable,
557
+ embeddings?: EmbeddingFunction<T>,
558
+ schema?: Schema,
559
+ ): Promise<Buffer> {
560
+ if (schema !== undefined && schema !== null) {
561
+ schema = sanitizeSchema(schema);
562
+ }
563
+ const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
564
+ const writer = RecordBatchFileWriter.writeAll(tableWithEmbeddings);
565
+ return Buffer.from(await writer.toUint8Array());
566
+ }
567
+
568
+ /**
569
+ * Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
570
+ *
571
+ * This function will apply `embeddings` to the table in a manner similar to
572
+ * `convertToTable`.
573
+ *
574
+ * `schema` is required if the table is empty
575
+ */
576
+ export async function fromDataToBuffer<T>(
577
+ data: Data,
578
+ embeddings?: EmbeddingFunction<T>,
579
+ schema?: Schema,
580
+ ): Promise<Buffer> {
581
+ if (schema !== undefined && schema !== null) {
582
+ schema = sanitizeSchema(schema);
583
+ }
584
+ if (data instanceof ArrowTable) {
585
+ return fromTableToBuffer(data, embeddings, schema);
586
+ } else {
587
+ const table = await convertToTable(data);
588
+ return fromTableToBuffer(table, embeddings, schema);
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Serialize an Arrow Table into a buffer using the Arrow IPC Stream serialization
594
+ *
595
+ * This function will apply `embeddings` to the table in a manner similar to
596
+ * `convertToTable`.
597
+ *
598
+ * `schema` is required if the table is empty
599
+ */
600
+ export async function fromTableToStreamBuffer<T>(
601
+ table: ArrowTable,
602
+ embeddings?: EmbeddingFunction<T>,
603
+ schema?: Schema,
604
+ ): Promise<Buffer> {
605
+ const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
606
+ const writer = RecordBatchStreamWriter.writeAll(tableWithEmbeddings);
607
+ return Buffer.from(await writer.toUint8Array());
608
+ }
609
+
610
+ /**
611
+ * Reorder the columns in `batch` so that they agree with the field order in `schema`
612
+ */
613
+ function alignBatch(batch: RecordBatch, schema: Schema): RecordBatch {
614
+ const alignedChildren = [];
615
+ for (const field of schema.fields) {
616
+ const indexInBatch = batch.schema.fields?.findIndex(
617
+ (f) => f.name === field.name,
618
+ );
619
+ if (indexInBatch < 0) {
620
+ throw new Error(
621
+ `The column ${field.name} was not found in the Arrow Table`,
622
+ );
623
+ }
624
+ alignedChildren.push(batch.data.children[indexInBatch]);
625
+ }
626
+ const newData = makeData({
627
+ type: new Struct(schema.fields),
628
+ length: batch.numRows,
629
+ nullCount: batch.nullCount,
630
+ children: alignedChildren,
631
+ });
632
+ return new RecordBatch(schema, newData);
633
+ }
634
+
635
+ /**
636
+ * Reorder the columns in `table` so that they agree with the field order in `schema`
637
+ */
638
+ function alignTable(table: ArrowTable, schema: Schema): ArrowTable {
639
+ const alignedBatches = table.batches.map((batch) =>
640
+ alignBatch(batch, schema),
641
+ );
642
+ return new ArrowTable(schema, alignedBatches);
643
+ }
644
+
645
+ /**
646
+ * Create an empty table with the given schema
647
+ */
648
+ export function createEmptyTable(schema: Schema): ArrowTable {
649
+ return new ArrowTable(sanitizeSchema(schema));
650
+ }