Elffuss BraidHub

kikocis/lancedb public

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