Elffuss BraidHub

kikocis/lancedb public

d4aef929e8cc · 36.4 KiBRawPermalink
1// Copyright 2023 LanceDB 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 { describe } from "mocha";
16import { track } from "temp";
17import * as chai from "chai";
18import * as chaiAsPromised from "chai-as-promised";
19
20import * as lancedb from "../index";
21import {
22 type AwsCredentials,
23 type EmbeddingFunction,
24 MetricType,
25 Query,
26 WriteMode,
27 DefaultWriteOptions,
28 isWriteOptions,
29 type LocalTable
30} from "../index";
31import {
32 FixedSizeList,
33 Field,
34 Int32,
35 makeVector,
36 Schema,
37 Utf8,
38 Table as ArrowTable,
39 vectorFromArray,
40 Float64,
41 Float32,
42 Float16,
43 Int64
44} from "apache-arrow";
45import type { RemoteRequest, RemoteResponse } from "../middleware";
46
47const expect = chai.expect;
48const assert = chai.assert;
49chai.use(chaiAsPromised);
50
51describe("LanceDB client", function () {
52 describe("when creating a connection to lancedb", function () {
53 it("should have a valid url", async function () {
54 const uri = await createTestDB();
55 const con = await lancedb.connect(uri);
56 assert.equal(con.uri, uri);
57 });
58
59 it("should accept an options object", async function () {
60 const uri = await createTestDB();
61 const con = await lancedb.connect({ uri });
62 assert.equal(con.uri, uri);
63 });
64
65 it("should accept custom aws credentials", async function () {
66 const uri = await createTestDB();
67 const awsCredentials: AwsCredentials = {
68 accessKeyId: "",
69 secretKey: ""
70 };
71 const con = await lancedb.connect({
72 uri,
73 awsCredentials
74 });
75 assert.equal(con.uri, uri);
76 });
77
78 it("should accept custom storage options", async function () {
79 const uri = await createTestDB();
80 const storageOptions = {
81 region: "us-west-2",
82 timeout: "30s"
83 };
84 const con = await lancedb.connect({
85 uri,
86 storageOptions
87 });
88 assert.equal(con.uri, uri);
89 });
90
91 it("should return the existing table names", async function () {
92 const uri = await createTestDB();
93 const con = await lancedb.connect(uri);
94 assert.deepEqual(await con.tableNames(), ["vectors"]);
95 });
96
97 it("read consistency level", async function () {
98 const uri = await createTestDB();
99 const db1 = await lancedb.connect({ uri });
100 const table1 = await db1.openTable("vectors");
101
102 const db2 = await lancedb.connect({
103 uri,
104 readConsistencyInterval: 0
105 })
106 const table2 = await db2.openTable("vectors");
107
108 assert.equal(await table2.countRows(), 2);
109 await table1.add([
110 {
111 id: 3,
112 name: 'name_2',
113 price: 10,
114 is_active: true,
115 vector: [ 0, 0.1 ]
116 },
117 ]);
118 assert.equal(await table2.countRows(), 3);
119 });
120 });
121
122 describe("when querying an existing dataset", function () {
123 it("should open a table", async function () {
124 const uri = await createTestDB();
125 const con = await lancedb.connect(uri);
126 const table = await con.openTable("vectors");
127 assert.equal(table.name, "vectors");
128 });
129
130 it("execute a query", async function () {
131 const uri = await createTestDB();
132 const con = await lancedb.connect(uri);
133 const table = await con.openTable("vectors");
134 const results = await table.search([0.1, 0.3]).execute();
135
136 assert.equal(results.length, 2);
137 assert.equal(results[0].price, 10);
138 const vector = results[0].vector as Float32Array;
139 assert.approximately(vector[0], 0.0, 0.2);
140 assert.approximately(vector[0], 0.1, 0.3);
141 });
142
143 it("limits # of results", async function () {
144 const uri = await createTestDB(2, 100);
145 const con = await lancedb.connect(uri);
146 const table = await con.openTable("vectors");
147 let results = await table.search([0.1, 0.3]).limit(1).execute();
148 assert.equal(results.length, 1);
149 assert.equal(results[0].id, 1);
150
151 // there is a default limit if unspecified
152 results = await table.search([0.1, 0.3]).execute();
153 assert.equal(results.length, 10);
154 });
155
156 it("uses a filter / where clause without vector search", async function () {
157 // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
158 const assertResults = (results: Array<Record<string, unknown>>) => {
159 assert.equal(results.length, 50);
160 };
161
162 const uri = await createTestDB(2, 100);
163 const con = await lancedb.connect(uri);
164 const table = (await con.openTable("vectors")) as LocalTable;
165 let results = await table.filter("id % 2 = 0").limit(100).execute();
166 assertResults(results);
167 results = await table.where("id % 2 = 0").limit(100).execute();
168 assertResults(results);
169
170 // Should reject a bad filter
171 await expect(table.filter("id % 2 = 0 AND").execute()).to.be.rejectedWith(
172 /.*sql parser error: Expected an expression:, found: EOF.*/
173 );
174 });
175
176 it("uses a filter / where clause", async function () {
177 // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
178 const assertResults = (results: Array<Record<string, unknown>>) => {
179 assert.equal(results.length, 1);
180 assert.equal(results[0].id, 2);
181 };
182
183 const uri = await createTestDB();
184 const con = await lancedb.connect(uri);
185 const table = await con.openTable("vectors");
186 let results = await table.search([0.1, 0.1]).filter("id == 2").execute();
187 assertResults(results);
188 results = await table.search([0.1, 0.1]).where("id == 2").execute();
189 assertResults(results);
190 });
191
192 it("should correctly process prefilter/postfilter", async function () {
193 const uri = await createTestDB(16, 300);
194 const con = await lancedb.connect(uri);
195 const table = await con.openTable("vectors");
196 await table.createIndex({
197 type: "ivf_pq",
198 column: "vector",
199 num_partitions: 2,
200 max_iters: 2,
201 num_sub_vectors: 2
202 });
203 // post filter should return less than the limit
204 let results = await table
205 .search(new Array(16).fill(0.1))
206 .limit(10)
207 .filter("id >= 10")
208 .prefilter(false)
209 .execute();
210 assert.isTrue(results.length < 10);
211
212 // pre filter should return exactly the limit
213 results = await table
214 .search(new Array(16).fill(0.1))
215 .limit(10)
216 .filter("id >= 10")
217 .prefilter(true)
218 .execute();
219 assert.isTrue(results.length === 10);
220 });
221
222 it("should allow creation and use of scalar indices", async function () {
223 const uri = await createTestDB(16, 300);
224 const con = await lancedb.connect(uri);
225 const table = await con.openTable("vectors");
226 await table.createScalarIndex("id", true);
227
228 // Prefiltering should still work the same
229 const results = await table
230 .search(new Array(16).fill(0.1))
231 .limit(10)
232 .filter("id >= 10")
233 .prefilter(true)
234 .execute();
235 assert.isTrue(results.length === 10);
236 });
237
238 it("select only a subset of columns", async function () {
239 const uri = await createTestDB();
240 const con = await lancedb.connect(uri);
241 const table = await con.openTable("vectors");
242 const results = await table
243 .search([0.1, 0.1])
244 .select(["is_active", "vector"])
245 .execute();
246 assert.equal(results.length, 2);
247 // vector and _distance are always returned
248 assert.isDefined(results[0].vector);
249 assert.isDefined(results[0]._distance);
250 assert.isDefined(results[0].is_active);
251
252 assert.isUndefined(results[0].id);
253 assert.isUndefined(results[0].name);
254 assert.isUndefined(results[0].price);
255 });
256 });
257
258 describe("when creating a new dataset", function () {
259 it("create an empty table", async function () {
260 const dir = await track().mkdir("lancejs");
261 const con = await lancedb.connect(dir);
262
263 const schema = new Schema([
264 new Field("id", new Int32()),
265 new Field("name", new Utf8())
266 ]);
267 const table = await con.createTable({
268 name: "vectors",
269 schema
270 });
271 assert.equal(table.name, "vectors");
272 assert.deepEqual(await con.tableNames(), ["vectors"]);
273 });
274
275 it("create a table with a schema and records", async function () {
276 const dir = await track().mkdir("lancejs");
277 const con = await lancedb.connect(dir);
278
279 const schema = new Schema([
280 new Field("id", new Int32()),
281 new Field("name", new Utf8()),
282 new Field(
283 "vector",
284 new FixedSizeList(2, new Field("item", new Float32(), true)),
285 false
286 )
287 ]);
288 const data = [
289 {
290 vector: [0.5, 0.2],
291 name: "foo",
292 id: 0
293 },
294 {
295 vector: [0.3, 0.1],
296 name: "bar",
297 id: 1
298 }
299 ];
300 // even thought the keys in data is out of order it should still work
301 const table = await con.createTable({
302 name: "vectors",
303 data,
304 schema
305 });
306 assert.equal(table.name, "vectors");
307 assert.deepEqual(await con.tableNames(), ["vectors"]);
308 });
309
310 it("create a table with a empty data array", async function () {
311 const dir = await track().mkdir("lancejs");
312 const con = await lancedb.connect(dir);
313
314 const schema = new Schema([
315 new Field("id", new Int32()),
316 new Field("name", new Utf8())
317 ]);
318 const table = await con.createTable({
319 name: "vectors",
320 schema,
321 data: []
322 });
323 assert.equal(table.name, "vectors");
324 assert.deepEqual(await con.tableNames(), ["vectors"]);
325 });
326
327 it("create a table from an Arrow Table", async function () {
328 const dir = await track().mkdir("lancejs");
329 // Also test the connect function with an object
330 const con = await lancedb.connect({ uri: dir });
331
332 const i32s = new Int32Array(new Array<number>(10));
333 const i32 = makeVector(i32s);
334
335 const data = new ArrowTable({ vector: i32 });
336
337 const table = await con.createTable({
338 name: "vectors",
339 data
340 });
341 assert.equal(table.name, "vectors");
342 assert.equal(await table.countRows(), 10);
343 assert.equal(await table.countRows("vector IS NULL"), 0);
344 assert.deepEqual(await con.tableNames(), ["vectors"]);
345 });
346
347 it("creates a new table from javascript objects", async function () {
348 const dir = await track().mkdir("lancejs");
349 const con = await lancedb.connect(dir);
350
351 const data = [
352 { id: 1, vector: [0.1, 0.2], price: 10 },
353 {
354 id: 2,
355 vector: [1.1, 1.2],
356 price: 50
357 }
358 ];
359
360 const tableName = `vectors_${Math.floor(Math.random() * 100)}`;
361 const table = await con.createTable(tableName, data);
362 assert.equal(table.name, tableName);
363 assert.equal(await table.countRows(), 2);
364 });
365
366 it("creates a new table from javascript objects with variable sized list", async function () {
367 const dir = await track().mkdir("lancejs");
368 const con = await lancedb.connect(dir);
369
370 const data = [
371 {
372 id: 1,
373 vector: [0.1, 0.2],
374 list_of_str: ["a", "b", "c"],
375 list_of_num: [1, 2, 3]
376 },
377 {
378 id: 2,
379 vector: [1.1, 1.2],
380 list_of_str: ["x", "y"],
381 list_of_num: [4, 5, 6]
382 }
383 ];
384
385 const tableName = "with_variable_sized_list";
386 const table = (await con.createTable(tableName, data)) as LocalTable;
387 assert.equal(table.name, tableName);
388 assert.equal(await table.countRows(), 2);
389 const rs = await table.filter("id>1").execute();
390 assert.equal(rs.length, 1);
391 assert.deepEqual(rs[0].list_of_str, ["x", "y"]);
392 assert.isTrue(rs[0].list_of_num instanceof Array);
393 });
394
395 it("create table from arrow table", async () => {
396 const dim = 128;
397 const total = 256;
398 const dir = await track().mkdir("lancejs");
399 const con = await lancedb.connect(dir);
400
401 const schema = new Schema([
402 new Field("id", new Int32()),
403 new Field(
404 "vector",
405 new FixedSizeList(dim, new Field("item", new Float16(), true)),
406 false
407 )
408 ]);
409 const data = lancedb.makeArrowTable(
410 Array.from(Array(total), (_, i) => ({
411 id: i,
412 vector: Array.from(Array(dim), Math.random)
413 })),
414 { schema }
415 );
416 const table = await con.createTable("f16", data);
417 assert.equal(table.name, "f16");
418 assert.equal(await table.countRows(), total);
419 assert.equal(await table.countRows("id < 5"), 5);
420 assert.deepEqual(await con.tableNames(), ["f16"]);
421 assert.deepEqual(await table.schema, schema);
422
423 await table.createIndex({
424 num_sub_vectors: 2,
425 num_partitions: 2,
426 type: "ivf_pq"
427 });
428
429 const q = Array.from(Array(dim), Math.random);
430 const r = await table.search(q).limit(5).execute();
431 assert.equal(r.length, 5);
432 r.forEach((v) => {
433 assert.equal(Object.prototype.hasOwnProperty.call(v, "vector"), true);
434 assert.equal(
435 v.vector?.constructor.name,
436 "Array",
437 "vector column is list of floats"
438 );
439 });
440 }).timeout(120000);
441
442 it("use overwrite flag to overwrite existing table", async function () {
443 const dir = await track().mkdir("lancejs");
444 const con = await lancedb.connect(dir);
445
446 const data = [
447 { id: 1, vector: [0.1, 0.2], price: 10 },
448 {
449 id: 2,
450 vector: [1.1, 1.2],
451 price: 50
452 }
453 ];
454
455 const tableName = "overwrite";
456 await con.createTable(tableName, data, { writeMode: WriteMode.Create });
457
458 const newData = [
459 { id: 1, vector: [0.1, 0.2], price: 10 },
460 { id: 2, vector: [1.1, 1.2], price: 50 },
461 {
462 id: 3,
463 vector: [1.1, 1.2],
464 price: 50
465 }
466 ];
467
468 await expect(con.createTable(tableName, newData)).to.be.rejectedWith(
469 Error,
470 "already exists"
471 );
472
473 const table = await con.createTable(tableName, newData, {
474 writeMode: WriteMode.Overwrite
475 });
476 assert.equal(table.name, tableName);
477 assert.equal(await table.countRows(), 3);
478 });
479
480 it("appends records to an existing table ", async function () {
481 const dir = await track().mkdir("lancejs");
482 const con = await lancedb.connect(dir);
483
484 const data = [
485 {
486 id: 1,
487 vector: [0.1, 0.2],
488 price: 10,
489 name: "a"
490 },
491 {
492 id: 2,
493 vector: [1.1, 1.2],
494 price: 50,
495 name: "b"
496 }
497 ];
498
499 const table = await con.createTable("vectors", data);
500 assert.equal(await table.countRows(), 2);
501
502 const dataAdd = [
503 {
504 id: 3,
505 vector: [2.1, 2.2],
506 price: 10,
507 name: "c"
508 },
509 {
510 id: 4,
511 vector: [3.1, 3.2],
512 price: 50,
513 name: "d"
514 }
515 ];
516 await table.add(dataAdd);
517 assert.equal(await table.countRows(), 4);
518 });
519
520 it("appends records with fields in a different order", async function () {
521 const dir = await track().mkdir("lancejs");
522 const con = await lancedb.connect(dir);
523
524 const data = [
525 {
526 id: 1,
527 vector: [0.1, 0.2],
528 price: 10,
529 name: "a"
530 },
531 {
532 id: 2,
533 vector: [1.1, 1.2],
534 price: 50,
535 name: "b"
536 }
537 ];
538
539 const table = await con.createTable("vectors", data);
540
541 const dataAdd = [
542 {
543 id: 3,
544 vector: [2.1, 2.2],
545 name: "c",
546 price: 10
547 },
548 {
549 id: 4,
550 vector: [3.1, 3.2],
551 name: "d",
552 price: 50
553 }
554 ];
555 await table.add(dataAdd);
556 assert.equal(await table.countRows(), 4);
557 });
558
559 it("overwrite all records in a table", async function () {
560 const uri = await createTestDB();
561 const con = await lancedb.connect(uri);
562
563 const table = await con.openTable("vectors");
564 assert.equal(await table.countRows(), 2);
565
566 const dataOver = [
567 {
568 vector: [2.1, 2.2],
569 price: 10,
570 name: "foo"
571 },
572 {
573 vector: [3.1, 3.2],
574 price: 50,
575 name: "bar"
576 }
577 ];
578 await table.overwrite(dataOver);
579 assert.equal(await table.countRows(), 2);
580 });
581
582 it("can merge insert records into the table", async function () {
583 const dir = await track().mkdir("lancejs");
584 const con = await lancedb.connect(dir);
585
586 const data = [
587 { id: 1, age: 1 },
588 { id: 2, age: 1 }
589 ];
590 const table = await con.createTable("my_table", data);
591
592 // insert if not exists
593 let newData = [
594 { id: 2, age: 2 },
595 { id: 3, age: 2 }
596 ];
597 await table.mergeInsert("id", newData, {
598 whenNotMatchedInsertAll: true
599 });
600 assert.equal(await table.countRows(), 3);
601 assert.equal(await table.countRows("age = 2"), 1);
602
603 // conditional update
604 newData = [
605 { id: 2, age: 3 },
606 { id: 3, age: 3 }
607 ];
608 await table.mergeInsert("id", newData, {
609 whenMatchedUpdateAll: "target.age = 1"
610 });
611 assert.equal(await table.countRows(), 3);
612 assert.equal(await table.countRows("age = 1"), 1);
613 assert.equal(await table.countRows("age = 3"), 1);
614
615 newData = [
616 { id: 3, age: 4 },
617 { id: 4, age: 4 }
618 ];
619 await table.mergeInsert("id", newData, {
620 whenNotMatchedInsertAll: true,
621 whenMatchedUpdateAll: true
622 });
623 assert.equal(await table.countRows(), 4);
624 assert.equal((await table.filter("age = 4").execute()).length, 2);
625
626 newData = [{ id: 5, age: 5 }];
627 await table.mergeInsert("id", newData, {
628 whenNotMatchedInsertAll: true,
629 whenMatchedUpdateAll: true,
630 whenNotMatchedBySourceDelete: "age < 4"
631 });
632 assert.equal(await table.countRows(), 3);
633
634 await table.mergeInsert("id", newData, {
635 whenNotMatchedInsertAll: true,
636 whenMatchedUpdateAll: true,
637 whenNotMatchedBySourceDelete: true
638 });
639 assert.equal(await table.countRows(), 1);
640 });
641
642 it("can update records in the table", async function () {
643 const uri = await createTestDB();
644 const con = await lancedb.connect(uri);
645
646 const table = await con.openTable("vectors");
647 assert.equal(await table.countRows(), 2);
648
649 await table.update({
650 where: "price = 10",
651 valuesSql: { price: "100" }
652 });
653 const results = await table.search([0.1, 0.2]).execute();
654 assert.equal(results[0].price, 100);
655 assert.equal(results[1].price, 11);
656 });
657
658 it("can update the records using a literal value", async function () {
659 const uri = await createTestDB();
660 const con = await lancedb.connect(uri);
661
662 const table = await con.openTable("vectors");
663 assert.equal(await table.countRows(), 2);
664
665 await table.update({
666 where: "price = 10",
667 values: { price: 100 }
668 });
669 const results = await table.search([0.1, 0.2]).execute();
670 assert.equal(results[0].price, 100);
671 assert.equal(results[1].price, 11);
672 });
673
674 it("can update every record in the table", async function () {
675 const uri = await createTestDB();
676 const con = await lancedb.connect(uri);
677
678 const table = await con.openTable("vectors");
679 assert.equal(await table.countRows(), 2);
680
681 await table.update({ valuesSql: { price: "100" } });
682 const results = await table.search([0.1, 0.2]).execute();
683
684 assert.equal(results[0].price, 100);
685 assert.equal(results[1].price, 100);
686 });
687
688 it("can delete records from a table", async function () {
689 const uri = await createTestDB();
690 const con = await lancedb.connect(uri);
691
692 const table = await con.openTable("vectors");
693 assert.equal(await table.countRows(), 2);
694
695 await table.delete("price = 10");
696 assert.equal(await table.countRows(), 1);
697 });
698 it("can manually provide embedding columns", async function () {
699 const uri = await createTestDB();
700 const con = await lancedb.connect(uri);
701 const schema = new Schema([
702 new Field("id", new Int32()),
703 new Field("text", new Utf8()),
704 new Field(
705 "vector",
706 new FixedSizeList(2, new Field("item", new Float32(), true))
707 )
708 ]);
709 const data = [
710 { id: 1, text: "foo", vector: [0.1, 0.2] },
711 { id: 2, text: "bar", vector: [0.3, 0.4] }
712 ];
713 let table = await con.createTable({
714 name: "embed_vectors",
715 data,
716 schema
717 });
718 assert.equal(table.name, "embed_vectors");
719 table = await con.openTable("embed_vectors");
720 assert.equal(await table.countRows(), 2);
721 });
722
723 it("will error if no implementation for embedding column found", async function () {
724 const uri = await createTestDB();
725 const con = await lancedb.connect(uri);
726 const schema = new Schema([
727 new Field("id", new Int32()),
728 new Field("text", new Utf8()),
729 new Field(
730 "vector",
731 new FixedSizeList(2, new Field("item", new Float32(), true))
732 )
733 ]);
734 const data = [
735 { id: 1, text: "foo" },
736 { id: 2, text: "bar" }
737 ];
738
739 const table = con.createTable({
740 name: "embed_vectors",
741 data,
742 schema
743 });
744 await assert.isRejected(table);
745 });
746 });
747
748 describe("when searching an empty dataset", function () {
749 it("should not fail", async function () {
750 const dir = await track().mkdir("lancejs");
751 const con = await lancedb.connect(dir);
752
753 const schema = new Schema([
754 new Field(
755 "vector",
756 new FixedSizeList(128, new Field("float32", new Float32()))
757 )
758 ]);
759 const table = await con.createTable({
760 name: "vectors",
761 schema
762 });
763 const result = await table.search(Array(128).fill(0.1)).execute();
764 assert.isEmpty(result);
765 });
766 });
767
768 describe("when searching an empty-after-delete dataset", function () {
769 it("should not fail", async function () {
770 const dir = await track().mkdir("lancejs");
771 const con = await lancedb.connect(dir);
772
773 const schema = new Schema([
774 new Field(
775 "vector",
776 new FixedSizeList(128, new Field("float32", new Float32()))
777 )
778 ]);
779 const table = await con.createTable({
780 name: "vectors",
781 schema
782 });
783 await table.add([{ vector: Array(128).fill(0.1) }]);
784 // https://github.com/lancedb/lance/issues/1635
785 await table.delete("true");
786 const result = await table.search(Array(128).fill(0.1)).execute();
787 assert.isEmpty(result);
788 });
789 });
790
791 describe("when creating a vector index", function () {
792 it("overwrite all records in a table", async function () {
793 const uri = await createTestDB(32, 300);
794 const con = await lancedb.connect(uri);
795 const table = await con.openTable("vectors");
796 await table.createIndex({
797 type: "ivf_pq",
798 column: "vector",
799 num_partitions: 2,
800 max_iters: 2,
801 num_sub_vectors: 2
802 });
803 }).timeout(10_000); // Timeout is high partially because GH macos runner is pretty slow
804
805 it("replace an existing index", async function () {
806 const uri = await createTestDB(16, 300);
807 const con = await lancedb.connect(uri);
808 const table = await con.openTable("vectors");
809
810 await table.createIndex({
811 type: "ivf_pq",
812 column: "vector",
813 num_partitions: 2,
814 max_iters: 2,
815 num_sub_vectors: 2
816 });
817
818 // Replace should fail if the index already exists
819 await expect(
820 table.createIndex({
821 type: "ivf_pq",
822 column: "vector",
823 num_partitions: 2,
824 max_iters: 2,
825 num_sub_vectors: 2,
826 replace: false
827 })
828 ).to.be.rejectedWith("LanceError(Index)");
829
830 // Default replace = true
831 await table.createIndex({
832 type: "ivf_pq",
833 column: "vector",
834 num_partitions: 2,
835 max_iters: 2,
836 num_sub_vectors: 2
837 });
838 }).timeout(50_000);
839
840 it("it should fail when the column is not a vector", async function () {
841 const uri = await createTestDB(32, 300);
842 const con = await lancedb.connect(uri);
843 const table = await con.openTable("vectors");
844 const createIndex = table.createIndex({
845 type: "ivf_pq",
846 column: "name",
847 num_partitions: 2,
848 max_iters: 2,
849 num_sub_vectors: 2
850 });
851 await expect(createIndex).to.be.rejectedWith(
852 "index cannot be created on the column `name` which has data type Utf8"
853 );
854 });
855
856 it("it should fail when num_partitions is invalid", async function () {
857 const uri = await createTestDB(32, 300);
858 const con = await lancedb.connect(uri);
859 const table = await con.openTable("vectors");
860 const createIndex = table.createIndex({
861 type: "ivf_pq",
862 column: "name",
863 num_partitions: -1,
864 max_iters: 2,
865 num_sub_vectors: 2
866 });
867 await expect(createIndex).to.be.rejectedWith(
868 "num_partitions: must be > 0"
869 );
870 });
871
872 it("should be able to list index and stats", async function () {
873 const uri = await createTestDB(32, 300);
874 const con = await lancedb.connect(uri);
875 const table = await con.openTable("vectors");
876 await table.createIndex({
877 type: "ivf_pq",
878 column: "vector",
879 num_partitions: 2,
880 max_iters: 2,
881 num_sub_vectors: 2
882 });
883
884 const indices = await table.listIndices();
885 expect(indices).to.have.lengthOf(1);
886 expect(indices[0].name).to.equal("vector_idx");
887 expect(indices[0].uuid).to.not.be.equal(undefined);
888 expect(indices[0].columns).to.have.lengthOf(1);
889 expect(indices[0].columns[0]).to.equal("vector");
890
891 const stats = await table.indexStats(indices[0].uuid);
892 expect(stats.numIndexedRows).to.equal(300);
893 expect(stats.numUnindexedRows).to.equal(0);
894 }).timeout(50_000);
895 });
896
897 describe("when using a custom embedding function", function () {
898 class TextEmbedding implements EmbeddingFunction<string> {
899 sourceColumn: string;
900
901 constructor(targetColumn: string) {
902 this.sourceColumn = targetColumn;
903 }
904
905 _embedding_map = new Map<string, number[]>([
906 ["foo", [2.1, 2.2]],
907 ["bar", [3.1, 3.2]]
908 ]);
909
910 async embed(data: string[]): Promise<number[][]> {
911 return data.map(
912 (datum) => this._embedding_map.get(datum) ?? [0.0, 0.0]
913 );
914 }
915 }
916
917 it("should encode the original data into embeddings", async function () {
918 const dir = await track().mkdir("lancejs");
919 const con = await lancedb.connect(dir);
920 const embeddings = new TextEmbedding("name");
921
922 const data = [
923 {
924 price: 10,
925 name: "foo"
926 },
927 {
928 price: 50,
929 name: "bar"
930 }
931 ];
932 const table = await con.createTable("vectors", data, embeddings, {
933 writeMode: WriteMode.Create
934 });
935 const results = await table.search("foo").execute();
936 assert.equal(results.length, 2);
937 });
938
939 it("should create embeddings for Arrow Table", async function () {
940 const dir = await track().mkdir("lancejs");
941 const con = await lancedb.connect(dir);
942 const embeddingFunction = new TextEmbedding("name");
943
944 const names = vectorFromArray(["foo", "bar"], new Utf8());
945 const data = new ArrowTable({ name: names });
946
947 const table = await con.createTable({
948 name: "vectors",
949 data,
950 embeddingFunction
951 });
952 assert.equal(table.name, "vectors");
953 const results = await table.search("foo").execute();
954 assert.equal(results.length, 2);
955 });
956 });
957
958 describe("when inspecting the schema", function () {
959 it("should return the schema", async function () {
960 const uri = await createTestDB();
961 const db = await lancedb.connect(uri);
962 // the fsl inner field must be named 'item' and be nullable
963 const expectedSchema = new Schema([
964 new Field("id", new Int32()),
965 new Field(
966 "vector",
967 new FixedSizeList(128, new Field("item", new Float32(), true))
968 ),
969 new Field("s", new Utf8())
970 ]);
971 const table = await db.createTable({
972 name: "some_table",
973 schema: expectedSchema
974 });
975 const schema = await table.schema;
976 assert.deepEqual(expectedSchema, schema);
977 });
978 });
979});
980
981describe("Remote LanceDB client", function () {
982 describe("when the server is not reachable", function () {
983 it("produces a network error", async function () {
984 const con = await lancedb.connect({
985 uri: "db://test-1234",
986 region: "asdfasfasfdf",
987 apiKey: "some-api-key"
988 });
989
990 // GET
991 try {
992 await con.tableNames();
993 } catch (err) {
994 expect(err).to.have.property(
995 "message",
996 "Network Error: getaddrinfo ENOTFOUND test-1234.asdfasfasfdf.api.lancedb.com"
997 );
998 }
999
1000 // POST
1001 try {
1002 await con.createTable({
1003 name: "vectors",
1004 schema: new Schema([])
1005 });
1006 } catch (err) {
1007 expect(err).to.have.property(
1008 "message",
1009 "Network Error: getaddrinfo ENOTFOUND test-1234.asdfasfasfdf.api.lancedb.com"
1010 );
1011 }
1012
1013 // Search
1014 const table = await con
1015 .withMiddleware(
1016 new (class {
1017 async onRemoteRequest(
1018 req: RemoteRequest,
1019 next: (req: RemoteRequest) => Promise<RemoteResponse>
1020 ) {
1021 // intercept call to check if the table exists and make the call succeed
1022 if (req.uri.endsWith("/describe/")) {
1023 return {
1024 status: 200,
1025 statusText: "OK",
1026 headers: new Map(),
1027 body: async () => ({})
1028 };
1029 }
1030
1031 return await next(req);
1032 }
1033 })()
1034 )
1035 .openTable("vectors");
1036
1037 try {
1038 await table.search([0.1, 0.3]).execute();
1039 } catch (err) {
1040 expect(err).to.have.property(
1041 "message",
1042 "Network Error: getaddrinfo ENOTFOUND test-1234.asdfasfasfdf.api.lancedb.com"
1043 );
1044 }
1045 });
1046 });
1047});
1048
1049describe("Query object", function () {
1050 it("sets custom parameters", async function () {
1051 const query = new Query([0.1, 0.3])
1052 .limit(1)
1053 .metricType(MetricType.Cosine)
1054 .refineFactor(100)
1055 .select(["a", "b"])
1056 .nprobes(20) as Record<string, any>;
1057 assert.equal(query._limit, 1);
1058 assert.equal(query._metricType, MetricType.Cosine);
1059 assert.equal(query._refineFactor, 100);
1060 assert.equal(query._nprobes, 20);
1061 assert.deepEqual(query._select, ["a", "b"]);
1062 });
1063});
1064
1065async function createTestDB(
1066 numDimensions: number = 2,
1067 numRows: number = 2
1068): Promise<string> {
1069 const dir = await track().mkdir("lancejs");
1070 const con = await lancedb.connect(dir);
1071
1072 const data = [];
1073 for (let i = 0; i < numRows; i++) {
1074 const vector = [];
1075 for (let j = 0; j < numDimensions; j++) {
1076 vector.push(i + j * 0.1);
1077 }
1078 data.push({
1079 id: i + 1,
1080 name: `name_${i}`,
1081 price: i + 10,
1082 is_active: i % 2 === 0,
1083 vector
1084 });
1085 }
1086
1087 await con.createTable("vectors", data);
1088 return dir;
1089}
1090
1091describe("Drop table", function () {
1092 it("drop a table", async function () {
1093 const dir = await track().mkdir("lancejs");
1094 const con = await lancedb.connect(dir);
1095
1096 const data = [
1097 {
1098 price: 10,
1099 name: "foo",
1100 vector: [1, 2, 3]
1101 },
1102 {
1103 price: 50,
1104 name: "bar",
1105 vector: [4, 5, 6]
1106 }
1107 ];
1108 await con.createTable("t1", data);
1109 await con.createTable("t2", data);
1110
1111 assert.deepEqual(await con.tableNames(), ["t1", "t2"]);
1112
1113 await con.dropTable("t1");
1114 assert.deepEqual(await con.tableNames(), ["t2"]);
1115 });
1116});
1117
1118describe("WriteOptions", function () {
1119 context("#isWriteOptions", function () {
1120 it("should not match empty object", function () {
1121 assert.equal(isWriteOptions({}), false);
1122 });
1123 it("should match write options", function () {
1124 assert.equal(isWriteOptions({ writeMode: WriteMode.Create }), true);
1125 });
1126 it("should match undefined write mode", function () {
1127 assert.equal(isWriteOptions({ writeMode: undefined }), true);
1128 });
1129 it("should match default write options", function () {
1130 assert.equal(isWriteOptions(new DefaultWriteOptions()), true);
1131 });
1132 });
1133});
1134
1135describe("Compact and cleanup", function () {
1136 it("can cleanup after compaction", async function () {
1137 const dir = await track().mkdir("lancejs");
1138 const con = await lancedb.connect(dir);
1139
1140 const data = [
1141 {
1142 price: 10,
1143 name: "foo",
1144 vector: [1, 2, 3]
1145 },
1146 {
1147 price: 50,
1148 name: "bar",
1149 vector: [4, 5, 6]
1150 }
1151 ];
1152 const table = (await con.createTable("t1", data)) as LocalTable;
1153
1154 const newData = [
1155 {
1156 price: 30,
1157 name: "baz",
1158 vector: [7, 8, 9]
1159 }
1160 ];
1161 await table.add(newData);
1162
1163 const compactionMetrics = await table.compactFiles({
1164 numThreads: 2
1165 });
1166 assert.equal(compactionMetrics.fragmentsRemoved, 2);
1167 assert.equal(compactionMetrics.fragmentsAdded, 1);
1168 assert.equal(await table.countRows(), 3);
1169
1170 await table.cleanupOldVersions();
1171 assert.equal(await table.countRows(), 3);
1172
1173 // should have no effect, but this validates the arguments are parsed.
1174 await table.compactFiles({
1175 targetRowsPerFragment: 102410,
1176 maxRowsPerGroup: 1024,
1177 materializeDeletions: true,
1178 materializeDeletionsThreshold: 0.5,
1179 numThreads: 2
1180 });
1181
1182 const cleanupMetrics = await table.cleanupOldVersions(0, true);
1183 assert.isAtLeast(cleanupMetrics.bytesRemoved, 1);
1184 assert.isAtLeast(cleanupMetrics.oldVersions, 1);
1185 assert.equal(await table.countRows(), 3);
1186 });
1187});
1188
1189describe("schema evolution", function () {
1190 // Create a new sample table
1191 it("can add a new column to the schema", async function () {
1192 const dir = await track().mkdir("lancejs");
1193 const con = await lancedb.connect(dir);
1194 const table = await con.createTable("vectors", [
1195 { id: 1n, vector: [0.1, 0.2] }
1196 ]);
1197
1198 await table.addColumns([
1199 { name: "price", valueSql: "cast(10.0 as float)" }
1200 ]);
1201
1202 const expectedSchema = new Schema([
1203 new Field("id", new Int64()),
1204 new Field(
1205 "vector",
1206 new FixedSizeList(2, new Field("item", new Float32(), true))
1207 ),
1208 new Field("price", new Float32())
1209 ]);
1210 expect(await table.schema).to.deep.equal(expectedSchema);
1211 });
1212
1213 it("can alter the columns in the schema", async function () {
1214 const dir = await track().mkdir("lancejs");
1215 const con = await lancedb.connect(dir);
1216 const schema = new Schema([
1217 new Field("id", new Int64(), false),
1218 new Field(
1219 "vector",
1220 new FixedSizeList(2, new Field("item", new Float32(), true))
1221 ),
1222 new Field("price", new Float64(), false)
1223 ]);
1224 const table = await con.createTable("vectors", [
1225 { id: 1n, vector: [0.1, 0.2], price: 10.0 }
1226 ]);
1227 expect(await table.schema).to.deep.equal(schema);
1228
1229 await table.alterColumns([
1230 { path: "id", rename: "new_id" },
1231 { path: "price", nullable: true }
1232 ]);
1233
1234 const expectedSchema = new Schema([
1235 new Field("new_id", new Int64(), false),
1236 new Field(
1237 "vector",
1238 new FixedSizeList(2, new Field("item", new Float32(), true))
1239 ),
1240 new Field("price", new Float64(), true)
1241 ]);
1242 expect(await table.schema).to.deep.equal(expectedSchema);
1243 });
1244
1245 it("can drop a column from the schema", async function () {
1246 const dir = await track().mkdir("lancejs");
1247 const con = await lancedb.connect(dir);
1248 const table = await con.createTable("vectors", [
1249 { id: 1n, vector: [0.1, 0.2] }
1250 ]);
1251 await table.dropColumns(["vector"]);
1252
1253 const expectedSchema = new Schema([new Field("id", new Int64(), false)]);
1254 expect(await table.schema).to.deep.equal(expectedSchema);
1255 });
1256});