Elffuss BraidHub

kikocis/lancedb public

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