diff --git a/nodejs/__test__/embedding.test.ts b/nodejs/__test__/embedding.test.ts index 45d171a3d..5b46d2ca1 100644 --- a/nodejs/__test__/embedding.test.ts +++ b/nodejs/__test__/embedding.test.ts @@ -13,9 +13,12 @@ import { Float64, Int32, Schema, + Table, Utf8, fromDataToBuffer, + makeArrowTable, tableFromIPC, + tableToIPC, } from "../lancedb/arrow"; import { EmbeddingFunction, LanceSchema } from "../lancedb/embedding"; import { getRegistry, register } from "../lancedb/embedding/registry"; @@ -139,6 +142,113 @@ describe("embedding functions", () => { expect(vectorsDefined).toEqual(new Array(5).fill(true)); }); + it("uses the incoming Arrow schema when overwriting an embedding table", async () => { + @register("overwrite-schema") + class TestEmbedding extends EmbeddingFunction { + ndims() { + return 1; + } + embeddingDataType() { + return new Float32(); + } + async computeSourceEmbeddings(values: string[]) { + return values.map((value) => [value.length]); + } + } + + const db = await connect(tmpDir.name); + const embedding = new TestEmbedding(); + const schema = LanceSchema({ + text: embedding.sourceField(new Utf8()), + vector: embedding.vectorField(), + }); + const table = await db.createTable("embeddings", [{ text: "old" }], { + schema, + }); + + await table.add([{ text: "new row" }], { mode: "overwrite" }); + const [embedded] = await table.query().toArray(); + expect([...embedded.vector]).toEqual([7]); + expect((await table.schema()).metadata.has("embedding_functions")).toBe( + true, + ); + + const incoming = makeArrowTable([{ text: "fresh", vector: null }], { + schema, + }); + await table.add(incoming, { mode: "overwrite" }); + const reopened = await db.openTable("embeddings"); + const [fresh] = await reopened.query().toArray(); + expect(fresh.text).toBe("fresh"); + expect(fresh.vector?.toJSON()).toEqual([5]); + + const replacementSchema = new Schema( + [new Field("replacement", new Utf8(), true)], + new Map([["schema-version", "v2"]]), + ); + const replacement = makeArrowTable([{ replacement: "new schema" }], { + schema: replacementSchema, + }); + await table.add(replacement, { mode: "overwrite" }); + + expect(await table.schema()).toEqual(replacementSchema); + const rows = await table.query().toArray(); + expect(rows.map((row) => row.toJSON())).toEqual([ + { replacement: "new schema" }, + ]); + }); + + it.each(["populated", "missing"])( + "overwrites from two Arrow IPC batches with %s vectors", + async (vectors) => { + class ProducerEmbedding extends EmbeddingFunction { + ndims() { + return 2; + } + embeddingDataType() { + return new Float32(); + } + async computeSourceEmbeddings(values: string[]) { + return values.map((value) => [value.length, value.length + 1]); + } + } + if (vectors === "missing") { + register()(ProducerEmbedding); + } + const embedding = new ProducerEmbedding(); + const schema = LanceSchema({ + text: embedding.sourceField(new Utf8()), + vector: embedding.vectorField(), + }); + const first = makeArrowTable( + [{ text: "first", vector: vectors === "missing" ? null : [17, 18] }], + { schema }, + ); + const second = makeArrowTable( + [{ text: "next", vector: vectors === "missing" ? null : [77, 78] }], + { schema }, + ); + const source = new Table(schema, [...first.batches, ...second.batches]); + const incoming = tableFromIPC(tableToIPC(source, "file")); + expect(incoming.batches).toHaveLength(2); + + const db = await connect(tmpDir.name); + const table = await db.createTable("arrow_import", [{ previous: true }]); + await table.add(incoming, { mode: "overwrite" }); + const reopened = await db.openTable("arrow_import"); + expect((await reopened.schema()).metadata).toEqual(schema.metadata); + const rows = await reopened.query().toArray(); + expect(rows).toHaveLength(2); + expect( + Object.fromEntries(rows.map((row) => [row.text, [...row.vector]])), + ).toEqual( + vectors === "missing" + ? { first: [5, 6], next: [4, 5] } + : { first: [17, 18], next: [77, 78] }, + ); + }, + ); + it("should be able to create an empty table with an embedding function", async () => { @register() class MockEmbeddingFunction extends EmbeddingFunction { diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index a7b0e5d86..b556d524e 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -1068,7 +1068,9 @@ async function applyEmbeddingsFromMetadata( schema: Schema, ): Promise { const registry = getRegistry(); - const functions = await registry.parseFunctions(schema.metadata); + const functions = parseEmbeddingMetadata( + schema.metadata.get("embedding_functions")!, + ); const columns = Object.fromEntries( table.schema.fields.map((field) => [ @@ -1077,41 +1079,35 @@ async function applyEmbeddingsFromMetadata( ]), ); - for (const functionEntry of functions.values()) { - const sourceColumn = columns[functionEntry.sourceColumn]; - const destColumn = functionEntry.vectorColumn; - if (sourceColumn === undefined) { + for (const { name, model, sourceColumn, vectorColumn } of functions) { + const existingColumn = columns[vectorColumn]; + if ( + table.numRows === 0 || + (existingColumn && existingColumn.nullCount !== existingColumn.length) + ) { + continue; + } + + const source = columns[sourceColumn]; + if (source === undefined) { throw new Error( - `Cannot apply embedding function because the source column '${functionEntry.sourceColumn}' was not present in the data`, + `Cannot apply embedding function because the source column '${sourceColumn}' was not present in the data`, ); } - - // Check if destination column exists and handle accordingly - if (columns[destColumn] !== undefined) { - const existingColumn = columns[destColumn]; - // If the column exists but is all null, we can fill it with embeddings - if (existingColumn.nullCount !== existingColumn.length) { - // Column has non-null values, skip embedding application - continue; - } + const provider = registry.get(name); + if (!provider) { + throw new Error(`Function "${name}" not found in registry`); } - - if (table.batches.length > 1) { - throw new Error( - "Internal error: `makeArrowTable` unexpectedly created a table with more than one batch", - ); - } - const values = sourceColumn.toArray(); - - const vectors = - await functionEntry.function.computeSourceEmbeddings(values); + const embedding = await provider.create(model); + const values = source.toArray(); + const vectors = await embedding.computeSourceEmbeddings(values); if (vectors.length !== values.length) { throw new Error( "Embedding function did not return an embedding for each input element", ); } let destType: DataType; - const dtype = schema.fields.find((f) => f.name === destColumn)!.type; + const dtype = schema.fields.find((f) => f.name === vectorColumn)!.type; if (isFixedSizeList(dtype)) { destType = sanitizeType(dtype); } else { @@ -1120,8 +1116,7 @@ async function applyEmbeddingsFromMetadata( dtype, ); } - const vector = makeVector(vectors, destType); - columns[destColumn] = vector; + columns[vectorColumn] = makeVector(vectors, destType); } // Add any missing columns from the schema as null vectors diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index a255df807..1efb2171b 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -29,6 +29,7 @@ import { dataTypeToJson, fromDataToBuffer, fromTableToBuffer, + isArrowTable, isMultiVector, makeEmptyTable, tableFromIPC, @@ -179,7 +180,7 @@ import { createAutoQuery, instanceOfFullTextQuery, } from "./query"; -import { sanitizeType } from "./sanitize"; +import { sanitizeSchema, sanitizeType } from "./sanitize"; import { QueryParameters, toParameterBuffer } from "./sql"; import { IntoSql, toSQL } from "./util"; export { IndexConfig } from "./native"; @@ -1842,7 +1843,10 @@ export class LocalTable extends Table { throw new Error("retries must be an integer between 0 and 255"); } const mode = options?.mode ?? "append"; - const schema = await this.schema(); + const schema = + mode === "overwrite" && isArrowTable(data) + ? sanitizeSchema(data.schema) + : await this.schema(); const buffer = await fromDataToBuffer(data, undefined, schema); // Wrap the user callback so a thrown error doesn't surface as an