| 1 | // Copyright 2024 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 * as fs from "fs"; |
| 16 | import * as path from "path"; |
| 17 | import * as tmp from "tmp"; |
| 18 | |
| 19 | import * as arrow13 from "apache-arrow-13"; |
| 20 | import * as arrow14 from "apache-arrow-14"; |
| 21 | import * as arrow15 from "apache-arrow-15"; |
| 22 | import * as arrow16 from "apache-arrow-16"; |
| 23 | import * as arrow17 from "apache-arrow-17"; |
| 24 | |
| 25 | import { Table, connect } from "../lancedb"; |
| 26 | import { |
| 27 | Table as ArrowTable, |
| 28 | Field, |
| 29 | FixedSizeList, |
| 30 | Float32, |
| 31 | Float64, |
| 32 | Int32, |
| 33 | Int64, |
| 34 | List, |
| 35 | Schema, |
| 36 | Utf8, |
| 37 | makeArrowTable, |
| 38 | } from "../lancedb/arrow"; |
| 39 | import { |
| 40 | EmbeddingFunction, |
| 41 | LanceSchema, |
| 42 | getRegistry, |
| 43 | register, |
| 44 | } from "../lancedb/embedding"; |
| 45 | import { Index } from "../lancedb/indices"; |
| 46 | |
| 47 | describe.each([arrow13, arrow14, arrow15, arrow16, arrow17])( |
| 48 | "Given a table", |
| 49 | // biome-ignore lint/suspicious/noExplicitAny: <explanation> |
| 50 | (arrow: any) => { |
| 51 | let tmpDir: tmp.DirResult; |
| 52 | let table: Table; |
| 53 | |
| 54 | const schema: |
| 55 | | import("apache-arrow-13").Schema |
| 56 | | import("apache-arrow-14").Schema |
| 57 | | import("apache-arrow-15").Schema |
| 58 | | import("apache-arrow-16").Schema |
| 59 | | import("apache-arrow-17").Schema = new arrow.Schema([ |
| 60 | new arrow.Field("id", new arrow.Float64(), true), |
| 61 | ]); |
| 62 | |
| 63 | beforeEach(async () => { |
| 64 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 65 | const conn = await connect(tmpDir.name); |
| 66 | table = await conn.createEmptyTable("some_table", schema); |
| 67 | }); |
| 68 | afterEach(() => tmpDir.removeCallback()); |
| 69 | |
| 70 | it("be displayable", async () => { |
| 71 | expect(table.display()).toMatch( |
| 72 | /NativeTable\(some_table, uri=.*, read_consistency_interval=None\)/, |
| 73 | ); |
| 74 | table.close(); |
| 75 | expect(table.display()).toBe("ClosedTable(some_table)"); |
| 76 | }); |
| 77 | |
| 78 | it("should let me add data", async () => { |
| 79 | await table.add([{ id: 1 }, { id: 2 }]); |
| 80 | await table.add([{ id: 1 }]); |
| 81 | await expect(table.countRows()).resolves.toBe(3); |
| 82 | }); |
| 83 | |
| 84 | it("should overwrite data if asked", async () => { |
| 85 | await table.add([{ id: 1 }, { id: 2 }]); |
| 86 | await table.add([{ id: 1 }], { mode: "overwrite" }); |
| 87 | await expect(table.countRows()).resolves.toBe(1); |
| 88 | }); |
| 89 | |
| 90 | it("should let me close the table", async () => { |
| 91 | expect(table.isOpen()).toBe(true); |
| 92 | table.close(); |
| 93 | expect(table.isOpen()).toBe(false); |
| 94 | expect(table.countRows()).rejects.toThrow("Table some_table is closed"); |
| 95 | }); |
| 96 | |
| 97 | it("should let me update values", async () => { |
| 98 | await table.add([{ id: 1 }]); |
| 99 | expect(await table.countRows("id == 1")).toBe(1); |
| 100 | expect(await table.countRows("id == 7")).toBe(0); |
| 101 | await table.update({ id: "7" }); |
| 102 | expect(await table.countRows("id == 1")).toBe(0); |
| 103 | expect(await table.countRows("id == 7")).toBe(1); |
| 104 | await table.add([{ id: 2 }]); |
| 105 | // Test Map as input |
| 106 | await table.update(new Map(Object.entries({ id: "10" })), { |
| 107 | where: "id % 2 == 0", |
| 108 | }); |
| 109 | expect(await table.countRows("id == 2")).toBe(0); |
| 110 | expect(await table.countRows("id == 7")).toBe(1); |
| 111 | expect(await table.countRows("id == 10")).toBe(1); |
| 112 | }); |
| 113 | |
| 114 | it("should let me update values with `values`", async () => { |
| 115 | await table.add([{ id: 1 }]); |
| 116 | expect(await table.countRows("id == 1")).toBe(1); |
| 117 | expect(await table.countRows("id == 7")).toBe(0); |
| 118 | await table.update({ values: { id: 7 } }); |
| 119 | expect(await table.countRows("id == 1")).toBe(0); |
| 120 | expect(await table.countRows("id == 7")).toBe(1); |
| 121 | await table.add([{ id: 2 }]); |
| 122 | // Test Map as input |
| 123 | await table.update({ |
| 124 | values: { |
| 125 | id: "10", |
| 126 | }, |
| 127 | where: "id % 2 == 0", |
| 128 | }); |
| 129 | expect(await table.countRows("id == 2")).toBe(0); |
| 130 | expect(await table.countRows("id == 7")).toBe(1); |
| 131 | expect(await table.countRows("id == 10")).toBe(1); |
| 132 | }); |
| 133 | |
| 134 | it("should let me update values with `valuesSql`", async () => { |
| 135 | await table.add([{ id: 1 }]); |
| 136 | expect(await table.countRows("id == 1")).toBe(1); |
| 137 | expect(await table.countRows("id == 7")).toBe(0); |
| 138 | await table.update({ |
| 139 | valuesSql: { |
| 140 | id: "7", |
| 141 | }, |
| 142 | }); |
| 143 | expect(await table.countRows("id == 1")).toBe(0); |
| 144 | expect(await table.countRows("id == 7")).toBe(1); |
| 145 | await table.add([{ id: 2 }]); |
| 146 | // Test Map as input |
| 147 | await table.update({ |
| 148 | valuesSql: { |
| 149 | id: "10", |
| 150 | }, |
| 151 | where: "id % 2 == 0", |
| 152 | }); |
| 153 | expect(await table.countRows("id == 2")).toBe(0); |
| 154 | expect(await table.countRows("id == 7")).toBe(1); |
| 155 | expect(await table.countRows("id == 10")).toBe(1); |
| 156 | }); |
| 157 | |
| 158 | // https://github.com/lancedb/lancedb/issues/1293 |
| 159 | test.each([new arrow.Float16(), new arrow.Float32(), new arrow.Float64()])( |
| 160 | "can create empty table with non default float type: %s", |
| 161 | async (floatType) => { |
| 162 | const db = await connect(tmpDir.name); |
| 163 | |
| 164 | const data = [ |
| 165 | { text: "hello", vector: Array(512).fill(1.0) }, |
| 166 | { text: "hello world", vector: Array(512).fill(1.0) }, |
| 167 | ]; |
| 168 | const f64Schema = new arrow.Schema([ |
| 169 | new arrow.Field("text", new arrow.Utf8(), true), |
| 170 | new arrow.Field( |
| 171 | "vector", |
| 172 | new arrow.FixedSizeList(512, new arrow.Field("item", floatType)), |
| 173 | true, |
| 174 | ), |
| 175 | ]); |
| 176 | |
| 177 | const f64Table = await db.createEmptyTable("f64", f64Schema, { |
| 178 | mode: "overwrite", |
| 179 | }); |
| 180 | try { |
| 181 | await f64Table.add(data); |
| 182 | const res = await f64Table.query().toArray(); |
| 183 | expect(res.length).toBe(2); |
| 184 | } catch (e) { |
| 185 | expect(e).toBeUndefined(); |
| 186 | } |
| 187 | }, |
| 188 | ); |
| 189 | |
| 190 | it("should return the table as an instance of an arrow table", async () => { |
| 191 | const arrowTbl = await table.toArrow(); |
| 192 | expect(arrowTbl).toBeInstanceOf(ArrowTable); |
| 193 | }); |
| 194 | }, |
| 195 | ); |
| 196 | |
| 197 | describe("merge insert", () => { |
| 198 | let tmpDir: tmp.DirResult; |
| 199 | let table: Table; |
| 200 | |
| 201 | beforeEach(async () => { |
| 202 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 203 | const conn = await connect(tmpDir.name); |
| 204 | |
| 205 | table = await conn.createTable("some_table", [ |
| 206 | { a: 1, b: "a" }, |
| 207 | { a: 2, b: "b" }, |
| 208 | { a: 3, b: "c" }, |
| 209 | ]); |
| 210 | }); |
| 211 | afterEach(() => tmpDir.removeCallback()); |
| 212 | |
| 213 | test("upsert", async () => { |
| 214 | const newData = [ |
| 215 | { a: 2, b: "x" }, |
| 216 | { a: 3, b: "y" }, |
| 217 | { a: 4, b: "z" }, |
| 218 | ]; |
| 219 | await table |
| 220 | .mergeInsert("a") |
| 221 | .whenMatchedUpdateAll() |
| 222 | .whenNotMatchedInsertAll() |
| 223 | .execute(newData); |
| 224 | const expected = [ |
| 225 | { a: 1, b: "a" }, |
| 226 | { a: 2, b: "x" }, |
| 227 | { a: 3, b: "y" }, |
| 228 | { a: 4, b: "z" }, |
| 229 | ]; |
| 230 | |
| 231 | expect( |
| 232 | JSON.parse(JSON.stringify((await table.toArrow()).toArray())), |
| 233 | ).toEqual(expected); |
| 234 | }); |
| 235 | test("conditional update", async () => { |
| 236 | const newData = [ |
| 237 | { a: 2, b: "x" }, |
| 238 | { a: 3, b: "y" }, |
| 239 | { a: 4, b: "z" }, |
| 240 | ]; |
| 241 | await table |
| 242 | .mergeInsert("a") |
| 243 | .whenMatchedUpdateAll({ where: "target.b = 'b'" }) |
| 244 | .execute(newData); |
| 245 | |
| 246 | const expected = [ |
| 247 | { a: 1, b: "a" }, |
| 248 | { a: 2, b: "x" }, |
| 249 | { a: 3, b: "c" }, |
| 250 | ]; |
| 251 | // round trip to arrow and back to json to avoid comparing arrow objects to js object |
| 252 | // biome-ignore lint/suspicious/noExplicitAny: test |
| 253 | let res: any[] = JSON.parse( |
| 254 | JSON.stringify((await table.toArrow()).toArray()), |
| 255 | ); |
| 256 | res = res.sort((a, b) => a.a - b.a); |
| 257 | |
| 258 | expect(res).toEqual(expected); |
| 259 | }); |
| 260 | |
| 261 | test("insert if not exists", async () => { |
| 262 | const newData = [ |
| 263 | { a: 2, b: "x" }, |
| 264 | { a: 3, b: "y" }, |
| 265 | { a: 4, b: "z" }, |
| 266 | ]; |
| 267 | await table.mergeInsert("a").whenNotMatchedInsertAll().execute(newData); |
| 268 | const expected = [ |
| 269 | { a: 1, b: "a" }, |
| 270 | { a: 2, b: "b" }, |
| 271 | { a: 3, b: "c" }, |
| 272 | { a: 4, b: "z" }, |
| 273 | ]; |
| 274 | // biome-ignore lint/suspicious/noExplicitAny: <explanation> |
| 275 | let res: any[] = JSON.parse( |
| 276 | JSON.stringify((await table.toArrow()).toArray()), |
| 277 | ); |
| 278 | res = res.sort((a, b) => a.a - b.a); |
| 279 | expect(res).toEqual(expected); |
| 280 | }); |
| 281 | test("replace range", async () => { |
| 282 | const newData = [ |
| 283 | { a: 2, b: "x" }, |
| 284 | { a: 4, b: "z" }, |
| 285 | ]; |
| 286 | await table |
| 287 | .mergeInsert("a") |
| 288 | .whenMatchedUpdateAll() |
| 289 | .whenNotMatchedInsertAll() |
| 290 | .whenNotMatchedBySourceDelete({ where: "a > 2" }) |
| 291 | .execute(newData); |
| 292 | |
| 293 | const expected = [ |
| 294 | { a: 1, b: "a" }, |
| 295 | { a: 2, b: "x" }, |
| 296 | { a: 4, b: "z" }, |
| 297 | ]; |
| 298 | // biome-ignore lint/suspicious/noExplicitAny: <explanation> |
| 299 | let res: any[] = JSON.parse( |
| 300 | JSON.stringify((await table.toArrow()).toArray()), |
| 301 | ); |
| 302 | res = res.sort((a, b) => a.a - b.a); |
| 303 | expect(res).toEqual(expected); |
| 304 | }); |
| 305 | test("replace range no condition", async () => { |
| 306 | const newData = [ |
| 307 | { a: 2, b: "x" }, |
| 308 | { a: 4, b: "z" }, |
| 309 | ]; |
| 310 | await table |
| 311 | .mergeInsert("a") |
| 312 | .whenMatchedUpdateAll() |
| 313 | .whenNotMatchedInsertAll() |
| 314 | .whenNotMatchedBySourceDelete() |
| 315 | .execute(newData); |
| 316 | |
| 317 | const expected = [ |
| 318 | { a: 2, b: "x" }, |
| 319 | { a: 4, b: "z" }, |
| 320 | ]; |
| 321 | |
| 322 | // biome-ignore lint/suspicious/noExplicitAny: test |
| 323 | let res: any[] = JSON.parse( |
| 324 | JSON.stringify((await table.toArrow()).toArray()), |
| 325 | ); |
| 326 | res = res.sort((a, b) => a.a - b.a); |
| 327 | expect(res).toEqual(expected); |
| 328 | }); |
| 329 | }); |
| 330 | |
| 331 | describe("When creating an index", () => { |
| 332 | let tmpDir: tmp.DirResult; |
| 333 | const schema = new Schema([ |
| 334 | new Field("id", new Int32(), true), |
| 335 | new Field("vec", new FixedSizeList(32, new Field("item", new Float32()))), |
| 336 | new Field("tags", new List(new Field("item", new Utf8(), true))), |
| 337 | ]); |
| 338 | let tbl: Table; |
| 339 | let queryVec: number[]; |
| 340 | |
| 341 | beforeEach(async () => { |
| 342 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 343 | const db = await connect(tmpDir.name); |
| 344 | const data = makeArrowTable( |
| 345 | Array(300) |
| 346 | .fill(1) |
| 347 | .map((_, i) => ({ |
| 348 | id: i, |
| 349 | vec: Array(32) |
| 350 | .fill(1) |
| 351 | .map(() => Math.random()), |
| 352 | tags: ["tag1", "tag2", "tag3"], |
| 353 | })), |
| 354 | { |
| 355 | schema, |
| 356 | }, |
| 357 | ); |
| 358 | queryVec = data.toArray()[5].vec.toJSON(); |
| 359 | tbl = await db.createTable("test", data); |
| 360 | }); |
| 361 | afterEach(() => tmpDir.removeCallback()); |
| 362 | |
| 363 | it("should create a vector index on vector columns", async () => { |
| 364 | await tbl.createIndex("vec"); |
| 365 | |
| 366 | // check index directory |
| 367 | const indexDir = path.join(tmpDir.name, "test.lance", "_indices"); |
| 368 | expect(fs.readdirSync(indexDir)).toHaveLength(1); |
| 369 | const indices = await tbl.listIndices(); |
| 370 | expect(indices.length).toBe(1); |
| 371 | expect(indices[0]).toEqual({ |
| 372 | name: "vec_idx", |
| 373 | indexType: "IvfPq", |
| 374 | columns: ["vec"], |
| 375 | }); |
| 376 | |
| 377 | // Search without specifying the column |
| 378 | let rst = await tbl |
| 379 | .query() |
| 380 | .limit(2) |
| 381 | .nearestTo(queryVec) |
| 382 | .distanceType("dot") |
| 383 | .toArrow(); |
| 384 | expect(rst.numRows).toBe(2); |
| 385 | |
| 386 | // Search using `vectorSearch` |
| 387 | rst = await tbl.vectorSearch(queryVec).limit(2).toArrow(); |
| 388 | expect(rst.numRows).toBe(2); |
| 389 | |
| 390 | // Search with specifying the column |
| 391 | const rst2 = await tbl |
| 392 | .query() |
| 393 | .limit(2) |
| 394 | .nearestTo(queryVec) |
| 395 | .column("vec") |
| 396 | .toArrow(); |
| 397 | expect(rst2.numRows).toBe(2); |
| 398 | expect(rst.toString()).toEqual(rst2.toString()); |
| 399 | |
| 400 | // test offset |
| 401 | rst = await tbl.query().limit(2).offset(1).nearestTo(queryVec).toArrow(); |
| 402 | expect(rst.numRows).toBe(1); |
| 403 | }); |
| 404 | |
| 405 | it("should allow parameters to be specified", async () => { |
| 406 | await tbl.createIndex("vec", { |
| 407 | config: Index.ivfPq({ |
| 408 | numPartitions: 10, |
| 409 | }), |
| 410 | }); |
| 411 | |
| 412 | // TODO: Verify parameters when we can load index config as part of list indices |
| 413 | }); |
| 414 | |
| 415 | it("should allow me to replace (or not) an existing index", async () => { |
| 416 | await tbl.createIndex("id"); |
| 417 | // Default is replace=true |
| 418 | await tbl.createIndex("id"); |
| 419 | await expect(tbl.createIndex("id", { replace: false })).rejects.toThrow( |
| 420 | "already exists", |
| 421 | ); |
| 422 | await tbl.createIndex("id", { replace: true }); |
| 423 | }); |
| 424 | |
| 425 | test("should create a scalar index on scalar columns", async () => { |
| 426 | await tbl.createIndex("id"); |
| 427 | const indexDir = path.join(tmpDir.name, "test.lance", "_indices"); |
| 428 | expect(fs.readdirSync(indexDir)).toHaveLength(1); |
| 429 | |
| 430 | for await (const r of tbl.query().where("id > 1").select(["id"])) { |
| 431 | expect(r.numRows).toBe(298); |
| 432 | } |
| 433 | // should also work with 'filter' alias |
| 434 | for await (const r of tbl.query().filter("id > 1").select(["id"])) { |
| 435 | expect(r.numRows).toBe(298); |
| 436 | } |
| 437 | }); |
| 438 | |
| 439 | test("create a bitmap index", async () => { |
| 440 | await tbl.createIndex("id", { |
| 441 | config: Index.bitmap(), |
| 442 | }); |
| 443 | const indexDir = path.join(tmpDir.name, "test.lance", "_indices"); |
| 444 | expect(fs.readdirSync(indexDir)).toHaveLength(1); |
| 445 | }); |
| 446 | |
| 447 | test("create a hnswPq index", async () => { |
| 448 | await tbl.createIndex("vec", { |
| 449 | config: Index.hnswPq({ |
| 450 | numPartitions: 10, |
| 451 | }), |
| 452 | }); |
| 453 | const indexDir = path.join(tmpDir.name, "test.lance", "_indices"); |
| 454 | expect(fs.readdirSync(indexDir)).toHaveLength(1); |
| 455 | }); |
| 456 | |
| 457 | test("create a HnswSq index", async () => { |
| 458 | await tbl.createIndex("vec", { |
| 459 | config: Index.hnswSq({ |
| 460 | numPartitions: 10, |
| 461 | }), |
| 462 | }); |
| 463 | const indexDir = path.join(tmpDir.name, "test.lance", "_indices"); |
| 464 | expect(fs.readdirSync(indexDir)).toHaveLength(1); |
| 465 | }); |
| 466 | |
| 467 | test("create a label list index", async () => { |
| 468 | await tbl.createIndex("tags", { |
| 469 | config: Index.labelList(), |
| 470 | }); |
| 471 | const indexDir = path.join(tmpDir.name, "test.lance", "_indices"); |
| 472 | expect(fs.readdirSync(indexDir)).toHaveLength(1); |
| 473 | }); |
| 474 | |
| 475 | test("should be able to get index stats", async () => { |
| 476 | await tbl.createIndex("id"); |
| 477 | |
| 478 | const stats = await tbl.indexStats("id_idx"); |
| 479 | expect(stats).toBeDefined(); |
| 480 | expect(stats?.numIndexedRows).toEqual(300); |
| 481 | expect(stats?.numUnindexedRows).toEqual(0); |
| 482 | expect(stats?.distanceType).toBeUndefined(); |
| 483 | expect(stats?.indexType).toEqual("BTREE"); |
| 484 | expect(stats?.numIndices).toEqual(1); |
| 485 | }); |
| 486 | |
| 487 | test("when getting stats on non-existent index", async () => { |
| 488 | const stats = await tbl.indexStats("some non-existent index"); |
| 489 | expect(stats).toBeUndefined(); |
| 490 | }); |
| 491 | |
| 492 | // TODO: Move this test to the query API test (making sure we can reject queries |
| 493 | // when the dimension is incorrect) |
| 494 | test("two columns with different dimensions", async () => { |
| 495 | const db = await connect(tmpDir.name); |
| 496 | const schema = new Schema([ |
| 497 | new Field("id", new Int32(), true), |
| 498 | new Field("vec", new FixedSizeList(32, new Field("item", new Float32()))), |
| 499 | new Field( |
| 500 | "vec2", |
| 501 | new FixedSizeList(64, new Field("item", new Float32())), |
| 502 | ), |
| 503 | ]); |
| 504 | const tbl = await db.createTable( |
| 505 | "two_vectors", |
| 506 | makeArrowTable( |
| 507 | Array(300) |
| 508 | .fill(1) |
| 509 | .map((_, i) => ({ |
| 510 | id: i, |
| 511 | vec: Array(32) |
| 512 | .fill(1) |
| 513 | .map(() => Math.random()), |
| 514 | vec2: Array(64) // different dimension |
| 515 | .fill(1) |
| 516 | .map(() => Math.random()), |
| 517 | })), |
| 518 | { schema }, |
| 519 | ), |
| 520 | ); |
| 521 | |
| 522 | // Only build index over v1 |
| 523 | await tbl.createIndex("vec", { |
| 524 | config: Index.ivfPq({ numPartitions: 2, numSubVectors: 2 }), |
| 525 | }); |
| 526 | |
| 527 | const rst = await tbl |
| 528 | .query() |
| 529 | .limit(2) |
| 530 | .nearestTo( |
| 531 | Array(32) |
| 532 | .fill(1) |
| 533 | .map(() => Math.random()), |
| 534 | ) |
| 535 | .toArrow(); |
| 536 | expect(rst.numRows).toBe(2); |
| 537 | |
| 538 | // Search with specifying the column |
| 539 | await expect( |
| 540 | tbl |
| 541 | .query() |
| 542 | .limit(2) |
| 543 | .nearestTo( |
| 544 | Array(64) |
| 545 | .fill(1) |
| 546 | .map(() => Math.random()), |
| 547 | ) |
| 548 | .column("vec") |
| 549 | .toArrow(), |
| 550 | ).rejects.toThrow(/.* query dim=64, expected vector dim=32.*/); |
| 551 | |
| 552 | const query64 = Array(64) |
| 553 | .fill(1) |
| 554 | .map(() => Math.random()); |
| 555 | const rst64Query = await tbl.query().limit(2).nearestTo(query64).toArrow(); |
| 556 | const rst64Search = await tbl |
| 557 | .query() |
| 558 | .limit(2) |
| 559 | .nearestTo(query64) |
| 560 | .column("vec2") |
| 561 | .toArrow(); |
| 562 | expect(rst64Query.toString()).toEqual(rst64Search.toString()); |
| 563 | expect(rst64Query.numRows).toBe(2); |
| 564 | }); |
| 565 | }); |
| 566 | |
| 567 | describe("Read consistency interval", () => { |
| 568 | let tmpDir: tmp.DirResult; |
| 569 | beforeEach(() => { |
| 570 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 571 | }); |
| 572 | afterEach(() => tmpDir.removeCallback()); |
| 573 | |
| 574 | // const intervals = [undefined, 0, 0.1]; |
| 575 | const intervals = [0]; |
| 576 | test.each(intervals)("read consistency interval %p", async (interval) => { |
| 577 | const db = await connect(tmpDir.name); |
| 578 | const table = await db.createTable("my_table", [{ id: 1 }]); |
| 579 | |
| 580 | const db2 = await connect(tmpDir.name, { |
| 581 | readConsistencyInterval: interval, |
| 582 | }); |
| 583 | const table2 = await db2.openTable("my_table"); |
| 584 | expect(await table2.countRows()).toEqual(await table.countRows()); |
| 585 | |
| 586 | await table.add([{ id: 2 }]); |
| 587 | |
| 588 | if (interval === undefined) { |
| 589 | expect(await table2.countRows()).toEqual(1); |
| 590 | // TODO: once we implement time travel we can uncomment this part of the test. |
| 591 | // await table2.checkout_latest(); |
| 592 | // expect(await table2.countRows()).toEqual(2); |
| 593 | } else if (interval === 0) { |
| 594 | expect(await table2.countRows()).toEqual(2); |
| 595 | } else { |
| 596 | // interval == 0.1 |
| 597 | expect(await table2.countRows()).toEqual(1); |
| 598 | await new Promise((r) => setTimeout(r, 100)); |
| 599 | expect(await table2.countRows()).toEqual(2); |
| 600 | } |
| 601 | }); |
| 602 | }); |
| 603 | |
| 604 | describe("schema evolution", function () { |
| 605 | let tmpDir: tmp.DirResult; |
| 606 | beforeEach(() => { |
| 607 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 608 | }); |
| 609 | afterEach(() => { |
| 610 | tmpDir.removeCallback(); |
| 611 | }); |
| 612 | |
| 613 | // Create a new sample table |
| 614 | it("can add a new column to the schema", async function () { |
| 615 | const con = await connect(tmpDir.name); |
| 616 | const table = await con.createTable("vectors", [ |
| 617 | { id: 1n, vector: [0.1, 0.2] }, |
| 618 | ]); |
| 619 | |
| 620 | await table.addColumns([ |
| 621 | { name: "price", valueSql: "cast(10.0 as float)" }, |
| 622 | ]); |
| 623 | |
| 624 | const expectedSchema = new Schema([ |
| 625 | new Field("id", new Int64(), true), |
| 626 | new Field( |
| 627 | "vector", |
| 628 | new FixedSizeList(2, new Field("item", new Float32(), true)), |
| 629 | true, |
| 630 | ), |
| 631 | new Field("price", new Float32(), false), |
| 632 | ]); |
| 633 | expect(await table.schema()).toEqual(expectedSchema); |
| 634 | }); |
| 635 | |
| 636 | it("can alter the columns in the schema", async function () { |
| 637 | const con = await connect(tmpDir.name); |
| 638 | const schema = new Schema([ |
| 639 | new Field("id", new Int64(), true), |
| 640 | new Field( |
| 641 | "vector", |
| 642 | new FixedSizeList(2, new Field("item", new Float32(), true)), |
| 643 | true, |
| 644 | ), |
| 645 | new Field("price", new Float64(), false), |
| 646 | ]); |
| 647 | const table = await con.createTable("vectors", [ |
| 648 | { id: 1n, vector: [0.1, 0.2] }, |
| 649 | ]); |
| 650 | // Can create a non-nullable column only through addColumns at the moment. |
| 651 | await table.addColumns([ |
| 652 | { name: "price", valueSql: "cast(10.0 as double)" }, |
| 653 | ]); |
| 654 | expect(await table.schema()).toEqual(schema); |
| 655 | |
| 656 | await table.alterColumns([ |
| 657 | { path: "id", rename: "new_id" }, |
| 658 | { path: "price", nullable: true }, |
| 659 | ]); |
| 660 | |
| 661 | const expectedSchema = new Schema([ |
| 662 | new Field("new_id", new Int64(), true), |
| 663 | new Field( |
| 664 | "vector", |
| 665 | new FixedSizeList(2, new Field("item", new Float32(), true)), |
| 666 | true, |
| 667 | ), |
| 668 | new Field("price", new Float64(), true), |
| 669 | ]); |
| 670 | expect(await table.schema()).toEqual(expectedSchema); |
| 671 | }); |
| 672 | |
| 673 | it("can drop a column from the schema", async function () { |
| 674 | const con = await connect(tmpDir.name); |
| 675 | const table = await con.createTable("vectors", [ |
| 676 | { id: 1n, vector: [0.1, 0.2] }, |
| 677 | ]); |
| 678 | await table.dropColumns(["vector"]); |
| 679 | |
| 680 | const expectedSchema = new Schema([new Field("id", new Int64(), true)]); |
| 681 | expect(await table.schema()).toEqual(expectedSchema); |
| 682 | }); |
| 683 | }); |
| 684 | |
| 685 | describe("when dealing with versioning", () => { |
| 686 | let tmpDir: tmp.DirResult; |
| 687 | beforeEach(() => { |
| 688 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 689 | }); |
| 690 | afterEach(() => { |
| 691 | tmpDir.removeCallback(); |
| 692 | }); |
| 693 | |
| 694 | it("can travel in time", async () => { |
| 695 | // Setup |
| 696 | const con = await connect(tmpDir.name); |
| 697 | const table = await con.createTable("vectors", [ |
| 698 | { id: 1n, vector: [0.1, 0.2] }, |
| 699 | ]); |
| 700 | const version = await table.version(); |
| 701 | await table.add([{ id: 2n, vector: [0.1, 0.2] }]); |
| 702 | expect(await table.countRows()).toBe(2); |
| 703 | // Make sure we can rewind |
| 704 | await table.checkout(version); |
| 705 | expect(await table.countRows()).toBe(1); |
| 706 | // Can't add data in time travel mode |
| 707 | await expect(table.add([{ id: 3n, vector: [0.1, 0.2] }])).rejects.toThrow( |
| 708 | "table cannot be modified when a specific version is checked out", |
| 709 | ); |
| 710 | // Can go back to normal mode |
| 711 | await table.checkoutLatest(); |
| 712 | expect(await table.countRows()).toBe(2); |
| 713 | // Should be able to add data again |
| 714 | await table.add([{ id: 2n, vector: [0.1, 0.2] }]); |
| 715 | expect(await table.countRows()).toBe(3); |
| 716 | // Now checkout and restore |
| 717 | await table.checkout(version); |
| 718 | await table.restore(); |
| 719 | expect(await table.countRows()).toBe(1); |
| 720 | // Should be able to add data |
| 721 | await table.add([{ id: 2n, vector: [0.1, 0.2] }]); |
| 722 | expect(await table.countRows()).toBe(2); |
| 723 | // Can't use restore if not checked out |
| 724 | await expect(table.restore()).rejects.toThrow( |
| 725 | "checkout before running restore", |
| 726 | ); |
| 727 | }); |
| 728 | }); |
| 729 | |
| 730 | describe("when optimizing a dataset", () => { |
| 731 | let tmpDir: tmp.DirResult; |
| 732 | let table: Table; |
| 733 | beforeEach(async () => { |
| 734 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 735 | const con = await connect(tmpDir.name); |
| 736 | table = await con.createTable("vectors", [{ id: 1 }]); |
| 737 | await table.add([{ id: 2 }]); |
| 738 | }); |
| 739 | afterEach(() => { |
| 740 | tmpDir.removeCallback(); |
| 741 | }); |
| 742 | |
| 743 | it("compacts files", async () => { |
| 744 | const stats = await table.optimize(); |
| 745 | expect(stats.compaction.filesAdded).toBe(1); |
| 746 | expect(stats.compaction.filesRemoved).toBe(2); |
| 747 | expect(stats.compaction.fragmentsAdded).toBe(1); |
| 748 | expect(stats.compaction.fragmentsRemoved).toBe(2); |
| 749 | }); |
| 750 | |
| 751 | it("cleanups old versions", async () => { |
| 752 | const stats = await table.optimize({ cleanupOlderThan: new Date() }); |
| 753 | expect(stats.prune.bytesRemoved).toBeGreaterThan(0); |
| 754 | expect(stats.prune.oldVersionsRemoved).toBe(3); |
| 755 | }); |
| 756 | |
| 757 | it("delete unverified", async () => { |
| 758 | const version = await table.version(); |
| 759 | const versionFile = `${tmpDir.name}/${table.name}.lance/_versions/${version - 1}.manifest`; |
| 760 | fs.rmSync(versionFile); |
| 761 | |
| 762 | let stats = await table.optimize({ deleteUnverified: false }); |
| 763 | expect(stats.prune.oldVersionsRemoved).toBe(0); |
| 764 | |
| 765 | stats = await table.optimize({ |
| 766 | cleanupOlderThan: new Date(), |
| 767 | deleteUnverified: true, |
| 768 | }); |
| 769 | expect(stats.prune.oldVersionsRemoved).toBeGreaterThan(1); |
| 770 | }); |
| 771 | }); |
| 772 | |
| 773 | describe.each([arrow13, arrow14, arrow15, arrow16, arrow17])( |
| 774 | "when optimizing a dataset", |
| 775 | // biome-ignore lint/suspicious/noExplicitAny: <explanation> |
| 776 | (arrow: any) => { |
| 777 | let tmpDir: tmp.DirResult; |
| 778 | beforeEach(() => { |
| 779 | getRegistry().reset(); |
| 780 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 781 | }); |
| 782 | afterEach(() => { |
| 783 | tmpDir.removeCallback(); |
| 784 | }); |
| 785 | |
| 786 | test("can search using a string", async () => { |
| 787 | @register() |
| 788 | class MockEmbeddingFunction extends EmbeddingFunction<string> { |
| 789 | toJSON(): object { |
| 790 | return {}; |
| 791 | } |
| 792 | ndims() { |
| 793 | return 1; |
| 794 | } |
| 795 | embeddingDataType() { |
| 796 | return new Float32(); |
| 797 | } |
| 798 | |
| 799 | // Hardcoded embeddings for the sake of testing |
| 800 | async computeQueryEmbeddings(_data: string) { |
| 801 | switch (_data) { |
| 802 | case "greetings": |
| 803 | return [0.1]; |
| 804 | case "farewell": |
| 805 | return [0.2]; |
| 806 | default: |
| 807 | return null as never; |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | // Hardcoded embeddings for the sake of testing |
| 812 | async computeSourceEmbeddings(data: string[]) { |
| 813 | return data.map((s) => { |
| 814 | switch (s) { |
| 815 | case "hello world": |
| 816 | return [0.1]; |
| 817 | case "goodbye world": |
| 818 | return [0.2]; |
| 819 | default: |
| 820 | return null as never; |
| 821 | } |
| 822 | }); |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | const func = new MockEmbeddingFunction(); |
| 827 | const schema = LanceSchema({ |
| 828 | text: func.sourceField(new arrow.Utf8()), |
| 829 | vector: func.vectorField(), |
| 830 | }); |
| 831 | const db = await connect(tmpDir.name); |
| 832 | const data = [{ text: "hello world" }, { text: "goodbye world" }]; |
| 833 | const table = await db.createTable("test", data, { schema }); |
| 834 | |
| 835 | const results = await table.search("greetings").toArray(); |
| 836 | expect(results[0].text).toBe(data[0].text); |
| 837 | |
| 838 | const results2 = await table.search("farewell").toArray(); |
| 839 | expect(results2[0].text).toBe(data[1].text); |
| 840 | }); |
| 841 | |
| 842 | test("rejects if no embedding function provided", async () => { |
| 843 | const db = await connect(tmpDir.name); |
| 844 | const data = [ |
| 845 | { text: "hello world", vector: [0.1, 0.2, 0.3] }, |
| 846 | { text: "goodbye world", vector: [0.4, 0.5, 0.6] }, |
| 847 | ]; |
| 848 | const table = await db.createTable("test", data); |
| 849 | |
| 850 | expect(table.search("hello", "vector").toArray()).rejects.toThrow( |
| 851 | "No embedding functions are defined in the table", |
| 852 | ); |
| 853 | }); |
| 854 | |
| 855 | test("full text search if no embedding function provided", async () => { |
| 856 | const db = await connect(tmpDir.name); |
| 857 | const data = [ |
| 858 | { text: "hello world", vector: [0.1, 0.2, 0.3] }, |
| 859 | { text: "goodbye world", vector: [0.4, 0.5, 0.6] }, |
| 860 | ]; |
| 861 | const table = await db.createTable("test", data); |
| 862 | await table.createIndex("text", { |
| 863 | config: Index.fts(), |
| 864 | }); |
| 865 | |
| 866 | const results = await table.search("hello").toArray(); |
| 867 | expect(results[0].text).toBe(data[0].text); |
| 868 | }); |
| 869 | |
| 870 | test("full text search without positions", async () => { |
| 871 | const db = await connect(tmpDir.name); |
| 872 | const data = [ |
| 873 | { text: "hello world", vector: [0.1, 0.2, 0.3] }, |
| 874 | { text: "goodbye world", vector: [0.4, 0.5, 0.6] }, |
| 875 | ]; |
| 876 | const table = await db.createTable("test", data); |
| 877 | await table.createIndex("text", { |
| 878 | config: Index.fts({ withPosition: false }), |
| 879 | }); |
| 880 | |
| 881 | const results = await table.search("hello").toArray(); |
| 882 | expect(results[0].text).toBe(data[0].text); |
| 883 | }); |
| 884 | |
| 885 | test("full text search phrase query", async () => { |
| 886 | const db = await connect(tmpDir.name); |
| 887 | const data = [ |
| 888 | { text: "hello world", vector: [0.1, 0.2, 0.3] }, |
| 889 | { text: "goodbye world", vector: [0.4, 0.5, 0.6] }, |
| 890 | ]; |
| 891 | const table = await db.createTable("test", data); |
| 892 | await table.createIndex("text", { |
| 893 | config: Index.fts(), |
| 894 | }); |
| 895 | |
| 896 | const results = await table.search("world").toArray(); |
| 897 | expect(results.length).toBe(2); |
| 898 | const phraseResults = await table.search('"hello world"').toArray(); |
| 899 | expect(phraseResults.length).toBe(1); |
| 900 | }); |
| 901 | |
| 902 | test.each([ |
| 903 | [0.4, 0.5, 0.599], // number[] |
| 904 | Float32Array.of(0.4, 0.5, 0.599), // Float32Array |
| 905 | Float64Array.of(0.4, 0.5, 0.599), // Float64Array |
| 906 | ])("can search using vectorlike datatypes", async (vectorlike) => { |
| 907 | const db = await connect(tmpDir.name); |
| 908 | const data = [ |
| 909 | { text: "hello world", vector: [0.1, 0.2, 0.3] }, |
| 910 | { text: "goodbye world", vector: [0.4, 0.5, 0.6] }, |
| 911 | ]; |
| 912 | const table = await db.createTable("test", data); |
| 913 | |
| 914 | // biome-ignore lint/suspicious/noExplicitAny: test |
| 915 | const results: any[] = await table.search(vectorlike).toArray(); |
| 916 | |
| 917 | expect(results.length).toBe(2); |
| 918 | expect(results[0].text).toBe(data[1].text); |
| 919 | }); |
| 920 | }, |
| 921 | ); |
| 922 | |
| 923 | describe("when calling explainPlan", () => { |
| 924 | let tmpDir: tmp.DirResult; |
| 925 | let table: Table; |
| 926 | let queryVec: number[]; |
| 927 | beforeEach(async () => { |
| 928 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 929 | const con = await connect(tmpDir.name); |
| 930 | table = await con.createTable("vectors", [{ id: 1, vector: [0.1, 0.2] }]); |
| 931 | }); |
| 932 | |
| 933 | afterEach(() => { |
| 934 | tmpDir.removeCallback(); |
| 935 | }); |
| 936 | |
| 937 | it("retrieves query plan", async () => { |
| 938 | queryVec = Array(2) |
| 939 | .fill(1) |
| 940 | .map(() => Math.random()); |
| 941 | const plan = await table.query().nearestTo(queryVec).explainPlan(true); |
| 942 | |
| 943 | expect(plan).toMatch("KNN"); |
| 944 | }); |
| 945 | }); |
| 946 | |
| 947 | describe("column name options", () => { |
| 948 | let tmpDir: tmp.DirResult; |
| 949 | let table: Table; |
| 950 | beforeEach(async () => { |
| 951 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); |
| 952 | const con = await connect(tmpDir.name); |
| 953 | table = await con.createTable("vectors", [ |
| 954 | { camelCase: 1, vector: [0.1, 0.2] }, |
| 955 | ]); |
| 956 | }); |
| 957 | |
| 958 | test("can select columns with different names", async () => { |
| 959 | const results = await table.query().select(["camelCase"]).toArray(); |
| 960 | expect(results[0].camelCase).toBe(1); |
| 961 | }); |
| 962 | |
| 963 | test("can filter on columns with different names", async () => { |
| 964 | const results = await table.query().where("`camelCase` = 1").toArray(); |
| 965 | expect(results[0].camelCase).toBe(1); |
| 966 | }); |
| 967 | }); |