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