Elffuss BraidHub

kikocis/lancedb public

0bc068462dda · 30.8 KiBRawPermalink
1// Copyright 2023 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {
16 Table as ArrowTable,
17 Binary,
18 BufferType,
19 DataType,
20 Field,
21 FixedSizeBinary,
22 FixedSizeList,
23 Float,
24 Float32,
25 Int,
26 LargeBinary,
27 List,
28 Null,
29 RecordBatch,
30 RecordBatchFileWriter,
31 RecordBatchStreamWriter,
32 Schema,
33 Struct,
34 Utf8,
35 Vector,
36 makeBuilder,
37 makeData,
38 type makeTable,
39 vectorFromArray,
40} from "apache-arrow";
41import { Buffers } from "apache-arrow/data";
42import { type EmbeddingFunction } from "./embedding/embedding_function";
43import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry";
44import {
45 sanitizeField,
46 sanitizeSchema,
47 sanitizeTable,
48 sanitizeType,
49} from "./sanitize";
50export * from "apache-arrow";
51export type SchemaLike =
52 | Schema
53 | {
54 fields: FieldLike[];
55 metadata: Map<string, string>;
56 get names(): unknown[];
57 };
58export type FieldLike =
59 | Field
60 | {
61 type: string;
62 name: string;
63 nullable?: boolean;
64 metadata?: Map<string, string>;
65 };
66
67export type DataLike =
68 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
69 | import("apache-arrow").Data<Struct<any>>
70 | {
71 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
72 type: any;
73 length: number;
74 offset: number;
75 stride: number;
76 nullable: boolean;
77 children: DataLike[];
78 get nullCount(): number;
79 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
80 values: Buffers<any>[BufferType.DATA];
81 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
82 typeIds: Buffers<any>[BufferType.TYPE];
83 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
84 nullBitmap: Buffers<any>[BufferType.VALIDITY];
85 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
86 valueOffsets: Buffers<any>[BufferType.OFFSET];
87 };
88
89export type RecordBatchLike =
90 | RecordBatch
91 | {
92 schema: SchemaLike;
93 data: DataLike;
94 };
95
96export type TableLike =
97 | ArrowTable
98 | { schema: SchemaLike; batches: RecordBatchLike[] };
99
100export type IntoVector =
101 | Float32Array
102 | Float64Array
103 | number[]
104 | Promise<Float32Array | Float64Array | number[]>;
105
106export function isArrowTable(value: object): value is TableLike {
107 if (value instanceof ArrowTable) return true;
108 return "schema" in value && "batches" in value;
109}
110
111export function isNull(value: unknown): value is Null {
112 return value instanceof Null || DataType.isNull(value);
113}
114export function isInt(value: unknown): value is Int {
115 return value instanceof Int || DataType.isInt(value);
116}
117export function isFloat(value: unknown): value is Float {
118 return value instanceof Float || DataType.isFloat(value);
119}
120export function isBinary(value: unknown): value is Binary {
121 return value instanceof Binary || DataType.isBinary(value);
122}
123export function isLargeBinary(value: unknown): value is LargeBinary {
124 return value instanceof LargeBinary || DataType.isLargeBinary(value);
125}
126export function isUtf8(value: unknown): value is Utf8 {
127 return value instanceof Utf8 || DataType.isUtf8(value);
128}
129export function isLargeUtf8(value: unknown): value is Utf8 {
130 return value instanceof Utf8 || DataType.isLargeUtf8(value);
131}
132export function isBool(value: unknown): value is Utf8 {
133 return value instanceof Utf8 || DataType.isBool(value);
134}
135export function isDecimal(value: unknown): value is Utf8 {
136 return value instanceof Utf8 || DataType.isDecimal(value);
137}
138export function isDate(value: unknown): value is Utf8 {
139 return value instanceof Utf8 || DataType.isDate(value);
140}
141export function isTime(value: unknown): value is Utf8 {
142 return value instanceof Utf8 || DataType.isTime(value);
143}
144export function isTimestamp(value: unknown): value is Utf8 {
145 return value instanceof Utf8 || DataType.isTimestamp(value);
146}
147export function isInterval(value: unknown): value is Utf8 {
148 return value instanceof Utf8 || DataType.isInterval(value);
149}
150export function isDuration(value: unknown): value is Utf8 {
151 return value instanceof Utf8 || DataType.isDuration(value);
152}
153export function isList(value: unknown): value is List {
154 return value instanceof List || DataType.isList(value);
155}
156export function isStruct(value: unknown): value is Struct {
157 return value instanceof Struct || DataType.isStruct(value);
158}
159export function isUnion(value: unknown): value is Struct {
160 return value instanceof Struct || DataType.isUnion(value);
161}
162export function isFixedSizeBinary(value: unknown): value is FixedSizeBinary {
163 return value instanceof FixedSizeBinary || DataType.isFixedSizeBinary(value);
164}
165
166export function isFixedSizeList(value: unknown): value is FixedSizeList {
167 return value instanceof FixedSizeList || DataType.isFixedSizeList(value);
168}
169
170/** Data type accepted by NodeJS SDK */
171export type Data = Record<string, unknown>[] | TableLike;
172
173/*
174 * Options to control how a column should be converted to a vector array
175 */
176export class VectorColumnOptions {
177 /** Vector column type. */
178 type: Float = new Float32();
179
180 constructor(values?: Partial<VectorColumnOptions>) {
181 Object.assign(this, values);
182 }
183}
184
185/** Options to control the makeArrowTable call. */
186export class MakeArrowTableOptions {
187 /*
188 * Schema of the data.
189 *
190 * If this is not provided then the data type will be inferred from the
191 * JS type. Integer numbers will become int64, floating point numbers
192 * will become float64 and arrays will become variable sized lists with
193 * the data type inferred from the first element in the array.
194 *
195 * The schema must be specified if there are no records (e.g. to make
196 * an empty table)
197 */
198 schema?: SchemaLike;
199
200 /*
201 * Mapping from vector column name to expected type
202 *
203 * Lance expects vector columns to be fixed size list arrays (i.e. tensors)
204 * However, `makeArrowTable` will not infer this by default (it creates
205 * variable size list arrays). This field can be used to indicate that a column
206 * should be treated as a vector column and converted to a fixed size list.
207 *
208 * The keys should be the names of the vector columns. The value specifies the
209 * expected data type of the vector columns.
210 *
211 * If `schema` is provided then this field is ignored.
212 *
213 * By default, the column named "vector" will be assumed to be a float32
214 * vector column.
215 */
216 vectorColumns: Record<string, VectorColumnOptions> = {
217 vector: new VectorColumnOptions(),
218 };
219 embeddings?: EmbeddingFunction<unknown>;
220 embeddingFunction?: EmbeddingFunctionConfig;
221
222 /**
223 * If true then string columns will be encoded with dictionary encoding
224 *
225 * Set this to true if your string columns tend to repeat the same values
226 * often. For more precise control use the `schema` property to specify the
227 * data type for individual columns.
228 *
229 * If `schema` is provided then this property is ignored.
230 */
231 dictionaryEncodeStrings: boolean = false;
232
233 constructor(values?: Partial<MakeArrowTableOptions>) {
234 Object.assign(this, values);
235 }
236}
237
238/**
239 * An enhanced version of the {@link makeTable} function from Apache Arrow
240 * that supports nested fields and embeddings columns.
241 *
242 * (typically you do not need to call this function. It will be called automatically
243 * when creating a table or adding data to it)
244 *
245 * This function converts an array of Record<String, any> (row-major JS objects)
246 * to an Arrow Table (a columnar structure)
247 *
248 * Note that it currently does not support nulls.
249 *
250 * If a schema is provided then it will be used to determine the resulting array
251 * types. Fields will also be reordered to fit the order defined by the schema.
252 *
253 * If a schema is not provided then the types will be inferred and the field order
254 * will be controlled by the order of properties in the first record. If a type
255 * is inferred it will always be nullable.
256 *
257 * If the input is empty then a schema must be provided to create an empty table.
258 *
259 * When a schema is not specified then data types will be inferred. The inference
260 * rules are as follows:
261 *
262 * - boolean => Bool
263 * - number => Float64
264 * - String => Utf8
265 * - Buffer => Binary
266 * - Record<String, any> => Struct
267 * - Array<any> => List
268 * @example
269 * import { fromTableToBuffer, makeArrowTable } from "../arrow";
270 * import { Field, FixedSizeList, Float16, Float32, Int32, Schema } from "apache-arrow";
271 *
272 * const schema = new Schema([
273 * new Field("a", new Int32()),
274 * new Field("b", new Float32()),
275 * new Field("c", new FixedSizeList(3, new Field("item", new Float16()))),
276 * ]);
277 * const table = makeArrowTable([
278 * { a: 1, b: 2, c: [1, 2, 3] },
279 * { a: 4, b: 5, c: [4, 5, 6] },
280 * { a: 7, b: 8, c: [7, 8, 9] },
281 * ], { schema });
282 * ```
283 *
284 * By default it assumes that the column named `vector` is a vector column
285 * and it will be converted into a fixed size list array of type float32.
286 * The `vectorColumns` option can be used to support other vector column
287 * names and data types.
288 *
289 * ```ts
290 *
291 * const schema = new Schema([
292 new Field("a", new Float64()),
293 new Field("b", new Float64()),
294 new Field(
295 "vector",
296 new FixedSizeList(3, new Field("item", new Float32()))
297 ),
298 ]);
299 const table = makeArrowTable([
300 { a: 1, b: 2, vector: [1, 2, 3] },
301 { a: 4, b: 5, vector: [4, 5, 6] },
302 { a: 7, b: 8, vector: [7, 8, 9] },
303 ]);
304 assert.deepEqual(table.schema, schema);
305 * ```
306 *
307 * You can specify the vector column types and names using the options as well
308 *
309 * ```typescript
310 *
311 * const schema = new Schema([
312 new Field('a', new Float64()),
313 new Field('b', new Float64()),
314 new Field('vec1', new FixedSizeList(3, new Field('item', new Float16()))),
315 new Field('vec2', new FixedSizeList(3, new Field('item', new Float16())))
316 ]);
317 * const table = makeArrowTable([
318 { a: 1, b: 2, vec1: [1, 2, 3], vec2: [2, 4, 6] },
319 { a: 4, b: 5, vec1: [4, 5, 6], vec2: [8, 10, 12] },
320 { a: 7, b: 8, vec1: [7, 8, 9], vec2: [14, 16, 18] }
321 ], {
322 vectorColumns: {
323 vec1: { type: new Float16() },
324 vec2: { type: new Float16() }
325 }
326 }
327 * assert.deepEqual(table.schema, schema)
328 * ```
329 */
330export function makeArrowTable(
331 data: Array<Record<string, unknown>>,
332 options?: Partial<MakeArrowTableOptions>,
333 metadata?: Map<string, string>,
334): ArrowTable {
335 if (
336 data.length === 0 &&
337 (options?.schema === undefined || options?.schema === null)
338 ) {
339 throw new Error("At least one record or a schema needs to be provided");
340 }
341
342 const opt = new MakeArrowTableOptions(options !== undefined ? options : {});
343 if (opt.schema !== undefined && opt.schema !== null) {
344 opt.schema = sanitizeSchema(opt.schema);
345 opt.schema = validateSchemaEmbeddings(
346 opt.schema as Schema,
347 data,
348 options?.embeddingFunction,
349 );
350 }
351 const columns: Record<string, Vector> = {};
352 // TODO: sample dataset to find missing columns
353 // Prefer the field ordering of the schema, if present
354 const columnNames =
355 opt.schema != null ? (opt.schema.names as string[]) : Object.keys(data[0]);
356 for (const colName of columnNames) {
357 if (
358 data.length !== 0 &&
359 !Object.prototype.hasOwnProperty.call(data[0], colName)
360 ) {
361 // The field is present in the schema, but not in the data, skip it
362 continue;
363 }
364 // Extract a single column from the records (transpose from row-major to col-major)
365 let values = data.map((datum) => datum[colName]);
366
367 // By default (type === undefined) arrow will infer the type from the JS type
368 let type;
369 if (opt.schema !== undefined) {
370 // If there is a schema provided, then use that for the type instead
371 type = opt.schema?.fields.filter((f) => f.name === colName)[0]?.type;
372 if (DataType.isInt(type) && type.bitWidth === 64) {
373 // wrap in BigInt to avoid bug: https://github.com/apache/arrow/issues/40051
374 values = values.map((v) => {
375 if (v === null) {
376 return v;
377 }
378 if (typeof v === "bigint") {
379 return v;
380 }
381 if (typeof v === "number") {
382 return BigInt(v);
383 }
384 throw new Error(
385 `Expected BigInt or number for column ${colName}, got ${typeof v}`,
386 );
387 });
388 }
389 } else {
390 // Otherwise, check to see if this column is one of the vector columns
391 // defined by opt.vectorColumns and, if so, use the fixed size list type
392 const vectorColumnOptions = opt.vectorColumns[colName];
393 if (vectorColumnOptions !== undefined) {
394 const firstNonNullValue = values.find((v) => v !== null);
395 if (Array.isArray(firstNonNullValue)) {
396 type = newVectorType(
397 firstNonNullValue.length,
398 vectorColumnOptions.type,
399 );
400 } else {
401 throw new Error(
402 `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`,
403 );
404 }
405 }
406 }
407
408 try {
409 // Convert an Array of JS values to an arrow vector
410 columns[colName] = makeVector(values, type, opt.dictionaryEncodeStrings);
411 } catch (error: unknown) {
412 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
413 throw Error(`Could not convert column "${colName}" to Arrow: ${error}`);
414 }
415 }
416
417 if (opt.schema != null) {
418 // `new ArrowTable(columns)` infers a schema which may sometimes have
419 // incorrect nullability (it assumes nullable=true always)
420 //
421 // `new ArrowTable(schema, columns)` will also fail because it will create a
422 // batch with an inferred schema and then complain that the batch schema
423 // does not match the provided schema.
424 //
425 // To work around this we first create a table with the wrong schema and
426 // then patch the schema of the batches so we can use
427 // `new ArrowTable(schema, batches)` which does not do any schema inference
428 const firstTable = new ArrowTable(columns);
429 const batchesFixed = firstTable.batches.map(
430 (batch) => new RecordBatch(opt.schema as Schema, batch.data),
431 );
432 let schema: Schema;
433 if (metadata !== undefined) {
434 let schemaMetadata = opt.schema.metadata;
435 if (schemaMetadata.size === 0) {
436 schemaMetadata = metadata;
437 } else {
438 for (const [key, entry] of schemaMetadata.entries()) {
439 schemaMetadata.set(key, entry);
440 }
441 }
442
443 schema = new Schema(opt.schema.fields as Field[], schemaMetadata);
444 } else {
445 schema = opt.schema as Schema;
446 }
447 return new ArrowTable(schema, batchesFixed);
448 }
449 const tbl = new ArrowTable(columns);
450 if (metadata !== undefined) {
451 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
452 (<any>tbl.schema).metadata = metadata;
453 }
454 return tbl;
455}
456
457/**
458 * Create an empty Arrow table with the provided schema
459 */
460export function makeEmptyTable(
461 schema: SchemaLike,
462 metadata?: Map<string, string>,
463): ArrowTable {
464 return makeArrowTable([], { schema }, metadata);
465}
466
467/**
468 * Helper function to convert Array<Array<any>> to a variable sized list array
469 */
470// @ts-expect-error (Vector<unknown> is not assignable to Vector<any>)
471function makeListVector(lists: unknown[][]): Vector<unknown> {
472 if (lists.length === 0 || lists[0].length === 0) {
473 throw Error("Cannot infer list vector from empty array or empty list");
474 }
475 const sampleList = lists[0];
476 // biome-ignore lint/suspicious/noExplicitAny: skip
477 let inferredType: any;
478 try {
479 const sampleVector = makeVector(sampleList);
480 inferredType = sampleVector.type;
481 } catch (error: unknown) {
482 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
483 throw Error(`Cannot infer list vector. Cannot infer inner type: ${error}`);
484 }
485
486 const listBuilder = makeBuilder({
487 type: new List(new Field("item", inferredType, true)),
488 });
489 for (const list of lists) {
490 listBuilder.append(list);
491 }
492 return listBuilder.finish().toVector();
493}
494
495/** Helper function to convert an Array of JS values to an Arrow Vector */
496function makeVector(
497 values: unknown[],
498 type?: DataType,
499 stringAsDictionary?: boolean,
500 // biome-ignore lint/suspicious/noExplicitAny: skip
501): Vector<any> {
502 if (type !== undefined) {
503 // No need for inference, let Arrow create it
504 return vectorFromArray(values, type);
505 }
506 if (values.length === 0) {
507 throw Error(
508 "makeVector requires at least one value or the type must be specfied",
509 );
510 }
511 const sampleValue = values.find((val) => val !== null && val !== undefined);
512 if (sampleValue === undefined) {
513 throw Error(
514 "makeVector cannot infer the type if all values are null or undefined",
515 );
516 }
517 if (Array.isArray(sampleValue)) {
518 // Default Arrow inference doesn't handle list types
519 return makeListVector(values as unknown[][]);
520 } else if (Buffer.isBuffer(sampleValue)) {
521 // Default Arrow inference doesn't handle Buffer
522 return vectorFromArray(values, new Binary());
523 } else if (
524 !(stringAsDictionary ?? false) &&
525 (typeof sampleValue === "string" || sampleValue instanceof String)
526 ) {
527 // If the type is string then don't use Arrow's default inference unless dictionaries are requested
528 // because it will always use dictionary encoding for strings
529 return vectorFromArray(values, new Utf8());
530 } else {
531 // Convert a JS array of values to an arrow vector
532 return vectorFromArray(values);
533 }
534}
535
536/** Helper function to apply embeddings from metadata to an input table */
537async function applyEmbeddingsFromMetadata(
538 table: ArrowTable,
539 schema: Schema,
540): Promise<ArrowTable> {
541 const registry = getRegistry();
542 const functions = await registry.parseFunctions(schema.metadata);
543
544 const columns = Object.fromEntries(
545 table.schema.fields.map((field) => [
546 field.name,
547 table.getChild(field.name)!,
548 ]),
549 );
550
551 for (const functionEntry of functions.values()) {
552 const sourceColumn = columns[functionEntry.sourceColumn];
553 const destColumn = functionEntry.vectorColumn ?? "vector";
554 if (sourceColumn === undefined) {
555 throw new Error(
556 `Cannot apply embedding function because the source column '${functionEntry.sourceColumn}' was not present in the data`,
557 );
558 }
559 if (columns[destColumn] !== undefined) {
560 throw new Error(
561 `Attempt to apply embeddings to table failed because column ${destColumn} already existed`,
562 );
563 }
564 if (table.batches.length > 1) {
565 throw new Error(
566 "Internal error: `makeArrowTable` unexpectedly created a table with more than one batch",
567 );
568 }
569 const values = sourceColumn.toArray();
570
571 const vectors =
572 await functionEntry.function.computeSourceEmbeddings(values);
573 if (vectors.length !== values.length) {
574 throw new Error(
575 "Embedding function did not return an embedding for each input element",
576 );
577 }
578 let destType: DataType;
579 const dtype = schema.fields.find((f) => f.name === destColumn)!.type;
580 if (isFixedSizeList(dtype)) {
581 destType = sanitizeType(dtype);
582 } else {
583 throw new Error(
584 "Expected FixedSizeList as datatype for vector field, instead got: " +
585 dtype,
586 );
587 }
588 const vector = makeVector(vectors, destType);
589 columns[destColumn] = vector;
590 }
591 const newTable = new ArrowTable(columns);
592 return alignTable(newTable, schema);
593}
594
595/** Helper function to apply embeddings to an input table */
596async function applyEmbeddings<T>(
597 table: ArrowTable,
598 embeddings?: EmbeddingFunctionConfig,
599 schema?: SchemaLike,
600): Promise<ArrowTable> {
601 if (schema !== undefined && schema !== null) {
602 schema = sanitizeSchema(schema);
603 }
604 if (schema?.metadata.has("embedding_functions")) {
605 return applyEmbeddingsFromMetadata(table, schema! as Schema);
606 } else if (embeddings == null || embeddings === undefined) {
607 return table;
608 }
609
610 // Convert from ArrowTable to Record<String, Vector>
611 const colEntries = [...Array(table.numCols).keys()].map((_, idx) => {
612 const name = table.schema.fields[idx].name;
613 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
614 const vec = table.getChildAt(idx)!;
615 return [name, vec];
616 });
617 const newColumns = Object.fromEntries(colEntries);
618
619 const sourceColumn = newColumns[embeddings.sourceColumn];
620 const destColumn = embeddings.vectorColumn ?? "vector";
621 const innerDestType =
622 embeddings.function.embeddingDataType() ?? new Float32();
623 if (sourceColumn === undefined) {
624 throw new Error(
625 `Cannot apply embedding function because the source column '${embeddings.sourceColumn}' was not present in the data`,
626 );
627 }
628
629 if (table.numRows === 0) {
630 if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
631 // We have an empty table and it already has the embedding column so no work needs to be done
632 // Note: we don't return an error like we did below because this is a common occurrence. For example,
633 // if we call convertToTable with 0 records and a schema that includes the embedding
634 return table;
635 }
636 const dimensions = embeddings.function.ndims();
637 if (dimensions !== undefined) {
638 const destType = newVectorType(dimensions, innerDestType);
639 newColumns[destColumn] = makeVector([], destType);
640 } else if (schema != null) {
641 const destField = schema.fields.find((f) => f.name === destColumn);
642 if (destField != null) {
643 newColumns[destColumn] = makeVector([], destField.type);
644 } else {
645 throw new Error(
646 `Attempt to apply embeddings to an empty table failed because schema was missing embedding column '${destColumn}'`,
647 );
648 }
649 } else {
650 throw new Error(
651 "Attempt to apply embeddings to an empty table when the embeddings function does not specify `embeddingDimension`",
652 );
653 }
654 } else {
655 if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
656 throw new Error(
657 `Attempt to apply embeddings to table failed because column ${destColumn} already existed`,
658 );
659 }
660 if (table.batches.length > 1) {
661 throw new Error(
662 "Internal error: `makeArrowTable` unexpectedly created a table with more than one batch",
663 );
664 }
665 const values = sourceColumn.toArray();
666 const vectors = await embeddings.function.computeSourceEmbeddings(
667 values as T[],
668 );
669 if (vectors.length !== values.length) {
670 throw new Error(
671 "Embedding function did not return an embedding for each input element",
672 );
673 }
674 const destType = newVectorType(vectors[0].length, innerDestType);
675 newColumns[destColumn] = makeVector(vectors, destType);
676 }
677
678 const newTable = new ArrowTable(newColumns);
679 if (schema != null) {
680 if (schema.fields.find((f) => f.name === destColumn) === undefined) {
681 throw new Error(
682 `When using embedding functions and specifying a schema the schema should include the embedding column but the column ${destColumn} was missing`,
683 );
684 }
685 return alignTable(newTable, schema as Schema);
686 }
687 return newTable;
688}
689
690/**
691 * Convert an Array of records into an Arrow Table, optionally applying an
692 * embeddings function to it.
693 *
694 * This function calls `makeArrowTable` first to create the Arrow Table.
695 * Any provided `makeTableOptions` (e.g. a schema) will be passed on to
696 * that call.
697 *
698 * The embedding function will be passed a column of values (based on the
699 * `sourceColumn` of the embedding function) and expects to receive back
700 * number[][] which will be converted into a fixed size list column. By
701 * default this will be a fixed size list of Float32 but that can be
702 * customized by the `embeddingDataType` property of the embedding function.
703 *
704 * If a schema is provided in `makeTableOptions` then it should include the
705 * embedding columns. If no schema is provded then embedding columns will
706 * be placed at the end of the table, after all of the input columns.
707 */
708export async function convertToTable(
709 data: Array<Record<string, unknown>>,
710 embeddings?: EmbeddingFunctionConfig,
711 makeTableOptions?: Partial<MakeArrowTableOptions>,
712): Promise<ArrowTable> {
713 const table = makeArrowTable(data, makeTableOptions);
714 return await applyEmbeddings(table, embeddings, makeTableOptions?.schema);
715}
716
717/** Creates the Arrow Type for a Vector column with dimension `dim` */
718export function newVectorType<T extends Float>(
719 dim: number,
720 innerType: unknown,
721): FixedSizeList<T> {
722 // in Lance we always default to have the elements nullable, so we need to set it to true
723 // otherwise we often get schema mismatches because the stored data always has schema with nullable elements
724 const children = new Field("item", <T>sanitizeType(innerType), true);
725 return new FixedSizeList(dim, children);
726}
727
728/**
729 * Serialize an Array of records into a buffer using the Arrow IPC File serialization
730 *
731 * This function will call `convertToTable` and pass on `embeddings` and `schema`
732 *
733 * `schema` is required if data is empty
734 */
735export async function fromRecordsToBuffer(
736 data: Array<Record<string, unknown>>,
737 embeddings?: EmbeddingFunctionConfig,
738 schema?: Schema,
739): Promise<Buffer> {
740 if (schema !== undefined && schema !== null) {
741 schema = sanitizeSchema(schema);
742 }
743 const table = await convertToTable(data, embeddings, { schema });
744 const writer = RecordBatchFileWriter.writeAll(table);
745 return Buffer.from(await writer.toUint8Array());
746}
747
748/**
749 * Serialize an Array of records into a buffer using the Arrow IPC Stream serialization
750 *
751 * This function will call `convertToTable` and pass on `embeddings` and `schema`
752 *
753 * `schema` is required if data is empty
754 */
755export async function fromRecordsToStreamBuffer(
756 data: Array<Record<string, unknown>>,
757 embeddings?: EmbeddingFunctionConfig,
758 schema?: Schema,
759): Promise<Buffer> {
760 if (schema !== undefined && schema !== null) {
761 schema = sanitizeSchema(schema);
762 }
763 const table = await convertToTable(data, embeddings, { schema });
764 const writer = RecordBatchStreamWriter.writeAll(table);
765 return Buffer.from(await writer.toUint8Array());
766}
767
768/**
769 * Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
770 *
771 * This function will apply `embeddings` to the table in a manner similar to
772 * `convertToTable`.
773 *
774 * `schema` is required if the table is empty
775 */
776export async function fromTableToBuffer(
777 table: ArrowTable,
778 embeddings?: EmbeddingFunctionConfig,
779 schema?: SchemaLike,
780): Promise<Buffer> {
781 if (schema !== undefined && schema !== null) {
782 schema = sanitizeSchema(schema);
783 }
784 const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
785 const writer = RecordBatchFileWriter.writeAll(tableWithEmbeddings);
786 return Buffer.from(await writer.toUint8Array());
787}
788
789/**
790 * Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
791 *
792 * This function will apply `embeddings` to the table in a manner similar to
793 * `convertToTable`.
794 *
795 * `schema` is required if the table is empty
796 */
797export async function fromDataToBuffer(
798 data: Data,
799 embeddings?: EmbeddingFunctionConfig,
800 schema?: Schema,
801): Promise<Buffer> {
802 if (schema !== undefined && schema !== null) {
803 schema = sanitizeSchema(schema);
804 }
805 if (isArrowTable(data)) {
806 return fromTableToBuffer(sanitizeTable(data), embeddings, schema);
807 } else {
808 const table = await convertToTable(data, embeddings, { schema });
809 return fromTableToBuffer(table);
810 }
811}
812
813/**
814 * Serialize an Arrow Table into a buffer using the Arrow IPC Stream serialization
815 *
816 * This function will apply `embeddings` to the table in a manner similar to
817 * `convertToTable`.
818 *
819 * `schema` is required if the table is empty
820 */
821export async function fromTableToStreamBuffer(
822 table: ArrowTable,
823 embeddings?: EmbeddingFunctionConfig,
824 schema?: SchemaLike,
825): Promise<Buffer> {
826 const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
827 const writer = RecordBatchStreamWriter.writeAll(tableWithEmbeddings);
828 return Buffer.from(await writer.toUint8Array());
829}
830
831/**
832 * Reorder the columns in `batch` so that they agree with the field order in `schema`
833 */
834function alignBatch(batch: RecordBatch, schema: Schema): RecordBatch {
835 const alignedChildren = [];
836 for (const field of schema.fields) {
837 const indexInBatch = batch.schema.fields?.findIndex(
838 (f) => f.name === field.name,
839 );
840 if (indexInBatch < 0) {
841 throw new Error(
842 `The column ${field.name} was not found in the Arrow Table`,
843 );
844 }
845 alignedChildren.push(batch.data.children[indexInBatch]);
846 }
847 const newData = makeData({
848 type: new Struct(schema.fields),
849 length: batch.numRows,
850 nullCount: batch.nullCount,
851 children: alignedChildren,
852 });
853 return new RecordBatch(schema, newData);
854}
855
856/**
857 * Reorder the columns in `table` so that they agree with the field order in `schema`
858 */
859function alignTable(table: ArrowTable, schema: Schema): ArrowTable {
860 const alignedBatches = table.batches.map((batch) =>
861 alignBatch(batch, schema),
862 );
863 return new ArrowTable(schema, alignedBatches);
864}
865
866/**
867 * Create an empty table with the given schema
868 */
869export function createEmptyTable(schema: Schema): ArrowTable {
870 return new ArrowTable(sanitizeSchema(schema));
871}
872
873function validateSchemaEmbeddings(
874 schema: Schema,
875 data: Array<Record<string, unknown>>,
876 embeddings: EmbeddingFunctionConfig | undefined,
877) {
878 const fields = [];
879 const missingEmbeddingFields = [];
880
881 // First we check if the field is a `FixedSizeList`
882 // Then we check if the data contains the field
883 // if it does not, we add it to the list of missing embedding fields
884 // Finally, we check if those missing embedding fields are `this._embeddings`
885 // if they are not, we throw an error
886 for (let field of schema.fields) {
887 if (isFixedSizeList(field.type)) {
888 field = sanitizeField(field);
889 if (data.length !== 0 && data?.[0]?.[field.name] === undefined) {
890 if (schema.metadata.has("embedding_functions")) {
891 const embeddings = JSON.parse(
892 schema.metadata.get("embedding_functions")!,
893 );
894 if (
895 // biome-ignore lint/suspicious/noExplicitAny: we don't know the type of `f`
896 embeddings.find((f: any) => f["vectorColumn"] === field.name) ===
897 undefined
898 ) {
899 missingEmbeddingFields.push(field);
900 }
901 } else {
902 missingEmbeddingFields.push(field);
903 }
904 } else {
905 fields.push(field);
906 }
907 } else {
908 fields.push(field);
909 }
910 }
911
912 if (missingEmbeddingFields.length > 0 && embeddings === undefined) {
913 throw new Error(
914 `Table has embeddings: "${missingEmbeddingFields
915 .map((f) => f.name)
916 .join(",")}", but no embedding function was provided`,
917 );
918 }
919
920 return new Schema(fields, schema.metadata);
921}