Elffuss BraidHub

kikocis/lancedb public

85830ec79fd2 · 28.7 KiBRawPermalink
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
15import * as fs from "fs";
16import * as path from "path";
17import * as tmp from "tmp";
18
19import * as arrow13 from "apache-arrow-13";
20import * as arrow14 from "apache-arrow-14";
21import * as arrow15 from "apache-arrow-15";
22import * as arrow16 from "apache-arrow-16";
23import * as arrow17 from "apache-arrow-17";
24
25import { Table, connect } from "../lancedb";
26import {
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";
39import {
40 EmbeddingFunction,
41 LanceSchema,
42 getRegistry,
43 register,
44} from "../lancedb/embedding";
45import { Index } from "../lancedb/indices";
46
47describe.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
197describe("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
331describe("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 });
483
484 test("when getting stats on non-existent index", async () => {
485 const stats = await tbl.indexStats("some non-existent index");
486 expect(stats).toBeUndefined();
487 });
488
489 // TODO: Move this test to the query API test (making sure we can reject queries
490 // when the dimension is incorrect)
491 test("two columns with different dimensions", async () => {
492 const db = await connect(tmpDir.name);
493 const schema = new Schema([
494 new Field("id", new Int32(), true),
495 new Field("vec", new FixedSizeList(32, new Field("item", new Float32()))),
496 new Field(
497 "vec2",
498 new FixedSizeList(64, new Field("item", new Float32())),
499 ),
500 ]);
501 const tbl = await db.createTable(
502 "two_vectors",
503 makeArrowTable(
504 Array(300)
505 .fill(1)
506 .map((_, i) => ({
507 id: i,
508 vec: Array(32)
509 .fill(1)
510 .map(() => Math.random()),
511 vec2: Array(64) // different dimension
512 .fill(1)
513 .map(() => Math.random()),
514 })),
515 { schema },
516 ),
517 );
518
519 // Only build index over v1
520 await tbl.createIndex("vec", {
521 config: Index.ivfPq({ numPartitions: 2, numSubVectors: 2 }),
522 });
523
524 const rst = await tbl
525 .query()
526 .limit(2)
527 .nearestTo(
528 Array(32)
529 .fill(1)
530 .map(() => Math.random()),
531 )
532 .toArrow();
533 expect(rst.numRows).toBe(2);
534
535 // Search with specifying the column
536 await expect(
537 tbl
538 .query()
539 .limit(2)
540 .nearestTo(
541 Array(64)
542 .fill(1)
543 .map(() => Math.random()),
544 )
545 .column("vec")
546 .toArrow(),
547 ).rejects.toThrow(/.* query dim=64, expected vector dim=32.*/);
548
549 const query64 = Array(64)
550 .fill(1)
551 .map(() => Math.random());
552 const rst64Query = await tbl.query().limit(2).nearestTo(query64).toArrow();
553 const rst64Search = await tbl
554 .query()
555 .limit(2)
556 .nearestTo(query64)
557 .column("vec2")
558 .toArrow();
559 expect(rst64Query.toString()).toEqual(rst64Search.toString());
560 expect(rst64Query.numRows).toBe(2);
561 });
562});
563
564describe("Read consistency interval", () => {
565 let tmpDir: tmp.DirResult;
566 beforeEach(() => {
567 tmpDir = tmp.dirSync({ unsafeCleanup: true });
568 });
569 afterEach(() => tmpDir.removeCallback());
570
571 // const intervals = [undefined, 0, 0.1];
572 const intervals = [0];
573 test.each(intervals)("read consistency interval %p", async (interval) => {
574 const db = await connect(tmpDir.name);
575 const table = await db.createTable("my_table", [{ id: 1 }]);
576
577 const db2 = await connect(tmpDir.name, {
578 readConsistencyInterval: interval,
579 });
580 const table2 = await db2.openTable("my_table");
581 expect(await table2.countRows()).toEqual(await table.countRows());
582
583 await table.add([{ id: 2 }]);
584
585 if (interval === undefined) {
586 expect(await table2.countRows()).toEqual(1);
587 // TODO: once we implement time travel we can uncomment this part of the test.
588 // await table2.checkout_latest();
589 // expect(await table2.countRows()).toEqual(2);
590 } else if (interval === 0) {
591 expect(await table2.countRows()).toEqual(2);
592 } else {
593 // interval == 0.1
594 expect(await table2.countRows()).toEqual(1);
595 await new Promise((r) => setTimeout(r, 100));
596 expect(await table2.countRows()).toEqual(2);
597 }
598 });
599});
600
601describe("schema evolution", function () {
602 let tmpDir: tmp.DirResult;
603 beforeEach(() => {
604 tmpDir = tmp.dirSync({ unsafeCleanup: true });
605 });
606 afterEach(() => {
607 tmpDir.removeCallback();
608 });
609
610 // Create a new sample table
611 it("can add a new column to the schema", async function () {
612 const con = await connect(tmpDir.name);
613 const table = await con.createTable("vectors", [
614 { id: 1n, vector: [0.1, 0.2] },
615 ]);
616
617 await table.addColumns([
618 { name: "price", valueSql: "cast(10.0 as float)" },
619 ]);
620
621 const expectedSchema = new Schema([
622 new Field("id", new Int64(), true),
623 new Field(
624 "vector",
625 new FixedSizeList(2, new Field("item", new Float32(), true)),
626 true,
627 ),
628 new Field("price", new Float32(), false),
629 ]);
630 expect(await table.schema()).toEqual(expectedSchema);
631 });
632
633 it("can alter the columns in the schema", async function () {
634 const con = await connect(tmpDir.name);
635 const schema = new Schema([
636 new Field("id", new Int64(), true),
637 new Field(
638 "vector",
639 new FixedSizeList(2, new Field("item", new Float32(), true)),
640 true,
641 ),
642 new Field("price", new Float64(), false),
643 ]);
644 const table = await con.createTable("vectors", [
645 { id: 1n, vector: [0.1, 0.2] },
646 ]);
647 // Can create a non-nullable column only through addColumns at the moment.
648 await table.addColumns([
649 { name: "price", valueSql: "cast(10.0 as double)" },
650 ]);
651 expect(await table.schema()).toEqual(schema);
652
653 await table.alterColumns([
654 { path: "id", rename: "new_id" },
655 { path: "price", nullable: true },
656 ]);
657
658 const expectedSchema = new Schema([
659 new Field("new_id", new Int64(), true),
660 new Field(
661 "vector",
662 new FixedSizeList(2, new Field("item", new Float32(), true)),
663 true,
664 ),
665 new Field("price", new Float64(), true),
666 ]);
667 expect(await table.schema()).toEqual(expectedSchema);
668 });
669
670 it("can drop a column from the schema", async function () {
671 const con = await connect(tmpDir.name);
672 const table = await con.createTable("vectors", [
673 { id: 1n, vector: [0.1, 0.2] },
674 ]);
675 await table.dropColumns(["vector"]);
676
677 const expectedSchema = new Schema([new Field("id", new Int64(), true)]);
678 expect(await table.schema()).toEqual(expectedSchema);
679 });
680});
681
682describe("when dealing with versioning", () => {
683 let tmpDir: tmp.DirResult;
684 beforeEach(() => {
685 tmpDir = tmp.dirSync({ unsafeCleanup: true });
686 });
687 afterEach(() => {
688 tmpDir.removeCallback();
689 });
690
691 it("can travel in time", async () => {
692 // Setup
693 const con = await connect(tmpDir.name);
694 const table = await con.createTable("vectors", [
695 { id: 1n, vector: [0.1, 0.2] },
696 ]);
697 const version = await table.version();
698 await table.add([{ id: 2n, vector: [0.1, 0.2] }]);
699 expect(await table.countRows()).toBe(2);
700 // Make sure we can rewind
701 await table.checkout(version);
702 expect(await table.countRows()).toBe(1);
703 // Can't add data in time travel mode
704 await expect(table.add([{ id: 3n, vector: [0.1, 0.2] }])).rejects.toThrow(
705 "table cannot be modified when a specific version is checked out",
706 );
707 // Can go back to normal mode
708 await table.checkoutLatest();
709 expect(await table.countRows()).toBe(2);
710 // Should be able to add data again
711 await table.add([{ id: 2n, vector: [0.1, 0.2] }]);
712 expect(await table.countRows()).toBe(3);
713 // Now checkout and restore
714 await table.checkout(version);
715 await table.restore();
716 expect(await table.countRows()).toBe(1);
717 // Should be able to add data
718 await table.add([{ id: 2n, vector: [0.1, 0.2] }]);
719 expect(await table.countRows()).toBe(2);
720 // Can't use restore if not checked out
721 await expect(table.restore()).rejects.toThrow(
722 "checkout before running restore",
723 );
724 });
725});
726
727describe("when optimizing a dataset", () => {
728 let tmpDir: tmp.DirResult;
729 let table: Table;
730 beforeEach(async () => {
731 tmpDir = tmp.dirSync({ unsafeCleanup: true });
732 const con = await connect(tmpDir.name);
733 table = await con.createTable("vectors", [{ id: 1 }]);
734 await table.add([{ id: 2 }]);
735 });
736 afterEach(() => {
737 tmpDir.removeCallback();
738 });
739
740 it("compacts files", async () => {
741 const stats = await table.optimize();
742 expect(stats.compaction.filesAdded).toBe(1);
743 expect(stats.compaction.filesRemoved).toBe(2);
744 expect(stats.compaction.fragmentsAdded).toBe(1);
745 expect(stats.compaction.fragmentsRemoved).toBe(2);
746 });
747
748 it("cleanups old versions", async () => {
749 const stats = await table.optimize({ cleanupOlderThan: new Date() });
750 expect(stats.prune.bytesRemoved).toBeGreaterThan(0);
751 expect(stats.prune.oldVersionsRemoved).toBe(3);
752 });
753
754 it("delete unverified", async () => {
755 const version = await table.version();
756 const versionFile = `${tmpDir.name}/${table.name}.lance/_versions/${version - 1}.manifest`;
757 fs.rmSync(versionFile);
758
759 let stats = await table.optimize({ deleteUnverified: false });
760 expect(stats.prune.oldVersionsRemoved).toBe(0);
761
762 stats = await table.optimize({
763 cleanupOlderThan: new Date(),
764 deleteUnverified: true,
765 });
766 expect(stats.prune.oldVersionsRemoved).toBeGreaterThan(1);
767 });
768});
769
770describe.each([arrow13, arrow14, arrow15, arrow16, arrow17])(
771 "when optimizing a dataset",
772 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
773 (arrow: any) => {
774 let tmpDir: tmp.DirResult;
775 beforeEach(() => {
776 getRegistry().reset();
777 tmpDir = tmp.dirSync({ unsafeCleanup: true });
778 });
779 afterEach(() => {
780 tmpDir.removeCallback();
781 });
782
783 test("can search using a string", async () => {
784 @register()
785 class MockEmbeddingFunction extends EmbeddingFunction<string> {
786 toJSON(): object {
787 return {};
788 }
789 ndims() {
790 return 1;
791 }
792 embeddingDataType() {
793 return new Float32();
794 }
795
796 // Hardcoded embeddings for the sake of testing
797 async computeQueryEmbeddings(_data: string) {
798 switch (_data) {
799 case "greetings":
800 return [0.1];
801 case "farewell":
802 return [0.2];
803 default:
804 return null as never;
805 }
806 }
807
808 // Hardcoded embeddings for the sake of testing
809 async computeSourceEmbeddings(data: string[]) {
810 return data.map((s) => {
811 switch (s) {
812 case "hello world":
813 return [0.1];
814 case "goodbye world":
815 return [0.2];
816 default:
817 return null as never;
818 }
819 });
820 }
821 }
822
823 const func = new MockEmbeddingFunction();
824 const schema = LanceSchema({
825 text: func.sourceField(new arrow.Utf8()),
826 vector: func.vectorField(),
827 });
828 const db = await connect(tmpDir.name);
829 const data = [{ text: "hello world" }, { text: "goodbye world" }];
830 const table = await db.createTable("test", data, { schema });
831
832 const results = await table.search("greetings").toArray();
833 expect(results[0].text).toBe(data[0].text);
834
835 const results2 = await table.search("farewell").toArray();
836 expect(results2[0].text).toBe(data[1].text);
837 });
838
839 test("rejects if no embedding function provided", async () => {
840 const db = await connect(tmpDir.name);
841 const data = [
842 { text: "hello world", vector: [0.1, 0.2, 0.3] },
843 { text: "goodbye world", vector: [0.4, 0.5, 0.6] },
844 ];
845 const table = await db.createTable("test", data);
846
847 expect(table.search("hello", "vector").toArray()).rejects.toThrow(
848 "No embedding functions are defined in the table",
849 );
850 });
851
852 test("full text search if no embedding function provided", async () => {
853 const db = await connect(tmpDir.name);
854 const data = [
855 { text: "hello world", vector: [0.1, 0.2, 0.3] },
856 { text: "goodbye world", vector: [0.4, 0.5, 0.6] },
857 ];
858 const table = await db.createTable("test", data);
859 await table.createIndex("text", {
860 config: Index.fts(),
861 });
862
863 const results = await table.search("hello").toArray();
864 expect(results[0].text).toBe(data[0].text);
865 });
866
867 test("full text search without positions", async () => {
868 const db = await connect(tmpDir.name);
869 const data = [
870 { text: "hello world", vector: [0.1, 0.2, 0.3] },
871 { text: "goodbye world", vector: [0.4, 0.5, 0.6] },
872 ];
873 const table = await db.createTable("test", data);
874 await table.createIndex("text", {
875 config: Index.fts({ withPosition: false }),
876 });
877
878 const results = await table.search("hello").toArray();
879 expect(results[0].text).toBe(data[0].text);
880 });
881
882 test("full text search phrase query", async () => {
883 const db = await connect(tmpDir.name);
884 const data = [
885 { text: "hello world", vector: [0.1, 0.2, 0.3] },
886 { text: "goodbye world", vector: [0.4, 0.5, 0.6] },
887 ];
888 const table = await db.createTable("test", data);
889 await table.createIndex("text", {
890 config: Index.fts(),
891 });
892
893 const results = await table.search("world").toArray();
894 expect(results.length).toBe(2);
895 const phraseResults = await table.search('"hello world"').toArray();
896 expect(phraseResults.length).toBe(1);
897 });
898
899 test.each([
900 [0.4, 0.5, 0.599], // number[]
901 Float32Array.of(0.4, 0.5, 0.599), // Float32Array
902 Float64Array.of(0.4, 0.5, 0.599), // Float64Array
903 ])("can search using vectorlike datatypes", async (vectorlike) => {
904 const db = await connect(tmpDir.name);
905 const data = [
906 { text: "hello world", vector: [0.1, 0.2, 0.3] },
907 { text: "goodbye world", vector: [0.4, 0.5, 0.6] },
908 ];
909 const table = await db.createTable("test", data);
910
911 // biome-ignore lint/suspicious/noExplicitAny: test
912 const results: any[] = await table.search(vectorlike).toArray();
913
914 expect(results.length).toBe(2);
915 expect(results[0].text).toBe(data[1].text);
916 });
917 },
918);
919
920describe("when calling explainPlan", () => {
921 let tmpDir: tmp.DirResult;
922 let table: Table;
923 let queryVec: number[];
924 beforeEach(async () => {
925 tmpDir = tmp.dirSync({ unsafeCleanup: true });
926 const con = await connect(tmpDir.name);
927 table = await con.createTable("vectors", [{ id: 1, vector: [0.1, 0.2] }]);
928 });
929
930 afterEach(() => {
931 tmpDir.removeCallback();
932 });
933
934 it("retrieves query plan", async () => {
935 queryVec = Array(2)
936 .fill(1)
937 .map(() => Math.random());
938 const plan = await table.query().nearestTo(queryVec).explainPlan(true);
939
940 expect(plan).toMatch("KNN");
941 });
942});
943
944describe("column name options", () => {
945 let tmpDir: tmp.DirResult;
946 let table: Table;
947 beforeEach(async () => {
948 tmpDir = tmp.dirSync({ unsafeCleanup: true });
949 const con = await connect(tmpDir.name);
950 table = await con.createTable("vectors", [
951 { camelCase: 1, vector: [0.1, 0.2] },
952 ]);
953 });
954
955 test("can select columns with different names", async () => {
956 const results = await table.query().select(["camelCase"]).toArray();
957 expect(results[0].camelCase).toBe(1);
958 });
959
960 test("can filter on columns with different names", async () => {
961 const results = await table.query().where("`camelCase` = 1").toArray();
962 expect(results[0].camelCase).toBe(1);
963 });
964});