@mastra/pinecone 0.0.0-a2a-20250421213654

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1548 @@
1
+ import type { QueryResult } from '@mastra/core/vector';
2
+ import dotenv from 'dotenv';
3
+ import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, afterEach } from 'vitest';
4
+
5
+ import { PineconeVector } from './';
6
+
7
+ dotenv.config();
8
+
9
+ const PINECONE_API_KEY = process.env.PINECONE_API_KEY!;
10
+
11
+ // if (!PINECONE_API_KEY) {
12
+ // throw new Error('Please set PINECONE_API_KEY and PINECONE_ENVIRONMENT in .env file');
13
+ // }
14
+ // TODO: skip until we the secrets on Github
15
+
16
+ vi.setConfig({ testTimeout: 80_000, hookTimeout: 80_000 });
17
+
18
+ // Helper function to create sparse vectors for testing
19
+ function createSparseVector(text: string) {
20
+ const words = text.toLowerCase().split(/\W+/).filter(Boolean);
21
+ const uniqueWords = Array.from(new Set(words));
22
+ const indices: number[] = [];
23
+ const values: number[] = [];
24
+
25
+ // Create a simple term frequency vector
26
+ uniqueWords.forEach((word, i) => {
27
+ const frequency = words.filter(w => w === word).length;
28
+ indices.push(i);
29
+ values.push(frequency);
30
+ });
31
+
32
+ return { indices, values };
33
+ }
34
+
35
+ function waitUntilReady(vectorDB: PineconeVector, indexName: string) {
36
+ return new Promise(resolve => {
37
+ const interval = setInterval(async () => {
38
+ try {
39
+ const stats = await vectorDB.describeIndex(indexName);
40
+ if (!!stats) {
41
+ clearInterval(interval);
42
+ resolve(true);
43
+ }
44
+ } catch (error) {
45
+ console.log(error);
46
+ }
47
+ }, 5000);
48
+ });
49
+ }
50
+
51
+ function waitUntilIndexDeleted(vectorDB: PineconeVector, indexName: string) {
52
+ return new Promise((resolve, reject) => {
53
+ const maxAttempts = 60;
54
+ let attempts = 0;
55
+
56
+ const interval = setInterval(async () => {
57
+ try {
58
+ const indexes = await vectorDB.listIndexes();
59
+ if (!indexes.includes(indexName)) {
60
+ clearInterval(interval);
61
+ resolve(true);
62
+ }
63
+ attempts++;
64
+ if (attempts >= maxAttempts) {
65
+ clearInterval(interval);
66
+ reject(new Error('Timeout waiting for index to be deleted'));
67
+ }
68
+ } catch (error) {
69
+ console.log(error);
70
+ }
71
+ }, 5000);
72
+ });
73
+ }
74
+
75
+ function waitUntilVectorsIndexed(
76
+ vectorDB: PineconeVector,
77
+ indexName: string,
78
+ expectedCount: number,
79
+ exactCount = false,
80
+ ) {
81
+ return new Promise((resolve, reject) => {
82
+ const maxAttempts = 60;
83
+ let attempts = 0;
84
+ let lastCount = 0;
85
+ let stableCount = 0;
86
+
87
+ const interval = setInterval(async () => {
88
+ try {
89
+ const stats = await vectorDB.describeIndex(indexName);
90
+ const check = exactCount ? stats?.count === expectedCount : stats?.count >= expectedCount;
91
+ if (stats && check) {
92
+ if (stats.count === lastCount) {
93
+ stableCount++;
94
+ if (stableCount >= 2) {
95
+ clearInterval(interval);
96
+ resolve(true);
97
+ }
98
+ } else {
99
+ stableCount = 1;
100
+ }
101
+ lastCount = stats.count;
102
+ }
103
+ attempts++;
104
+ if (attempts >= maxAttempts) {
105
+ clearInterval(interval);
106
+ reject(new Error('Timeout waiting for vectors to be indexed'));
107
+ }
108
+ } catch (error) {
109
+ console.log(error);
110
+ }
111
+ }, 10000);
112
+ });
113
+ }
114
+ // TODO: our pinecone account is over the limit, tests don't work in CI
115
+ describe.skip('PineconeVector Integration Tests', () => {
116
+ let vectorDB: PineconeVector;
117
+ const testIndexName = 'test-index'; // Unique index name for each test run
118
+ const indexNameUpdate = 'test-index-update';
119
+ const indexNameDelete = 'test-index-delete';
120
+ const indexNameNamespace = 'test-index-namespace';
121
+ const indexNameHybrid = 'test-index-hybrid';
122
+ const dimension = 3;
123
+
124
+ beforeAll(async () => {
125
+ vectorDB = new PineconeVector(PINECONE_API_KEY);
126
+ // Delete test index
127
+ try {
128
+ await vectorDB.deleteIndex(testIndexName);
129
+ await waitUntilIndexDeleted(vectorDB, testIndexName);
130
+ } catch {
131
+ // Ignore errors if index doesn't exist
132
+ }
133
+ try {
134
+ await vectorDB.deleteIndex(indexNameUpdate);
135
+ await waitUntilIndexDeleted(vectorDB, indexNameUpdate);
136
+ } catch {
137
+ // Ignore errors if index doesn't exist
138
+ }
139
+ try {
140
+ await vectorDB.deleteIndex(indexNameDelete);
141
+ await waitUntilIndexDeleted(vectorDB, indexNameDelete);
142
+ } catch {
143
+ // Ignore errors if index doesn't exist
144
+ }
145
+ try {
146
+ await vectorDB.deleteIndex(indexNameNamespace);
147
+ await waitUntilIndexDeleted(vectorDB, indexNameNamespace);
148
+ } catch {
149
+ // Ignore errors if index doesn't exist
150
+ }
151
+ try {
152
+ await vectorDB.deleteIndex(indexNameHybrid);
153
+ await waitUntilIndexDeleted(vectorDB, indexNameHybrid);
154
+ } catch {
155
+ // Ignore errors if index doesn't exist
156
+ }
157
+ // Create test index
158
+ await vectorDB.createIndex({ indexName: testIndexName, dimension });
159
+ await waitUntilReady(vectorDB, testIndexName);
160
+ }, 500000);
161
+
162
+ afterAll(async () => {
163
+ // Cleanup: delete test index
164
+ try {
165
+ await vectorDB.deleteIndex(testIndexName);
166
+ } catch {
167
+ // Ignore errors if index doesn't exist
168
+ }
169
+ try {
170
+ await vectorDB.deleteIndex(indexNameUpdate);
171
+ } catch {
172
+ // Ignore errors if index doesn't exist
173
+ }
174
+ try {
175
+ await vectorDB.deleteIndex(indexNameDelete);
176
+ } catch {
177
+ // Ignore errors if index doesn't exist
178
+ }
179
+ try {
180
+ await vectorDB.deleteIndex(indexNameNamespace);
181
+ } catch {
182
+ // Ignore errors if index doesn't exist
183
+ }
184
+ try {
185
+ await vectorDB.deleteIndex(indexNameHybrid);
186
+ } catch {
187
+ // Ignore errors if index doesn't exist
188
+ }
189
+ }, 500000);
190
+
191
+ describe('Index Operations', () => {
192
+ it('should list indexes including our test index', async () => {
193
+ const indexes = await vectorDB.listIndexes();
194
+ expect(indexes).toContain(testIndexName);
195
+ }, 500000);
196
+
197
+ it('should describe index with correct properties', async () => {
198
+ const stats = await vectorDB.describeIndex(testIndexName);
199
+ expect(stats.dimension).toBe(dimension);
200
+ expect(stats.metric).toBe('cosine');
201
+ expect(typeof stats.count).toBe('number');
202
+ }, 500000);
203
+ });
204
+
205
+ describe('Vector Operations', () => {
206
+ const testVectors = [
207
+ [1.0, 0.0, 0.0],
208
+ [0.0, 1.0, 0.0],
209
+ [0.0, 0.0, 1.0],
210
+ ];
211
+ const testMetadata = [{ label: 'x-axis' }, { label: 'y-axis' }, { label: 'z-axis' }];
212
+ let vectorIds: string[];
213
+
214
+ it('should upsert vectors with metadata', async () => {
215
+ vectorIds = await vectorDB.upsert({ indexName: testIndexName, vectors: testVectors, metadata: testMetadata });
216
+ expect(vectorIds).toHaveLength(3);
217
+ // Wait for vectors to be indexed
218
+ await waitUntilVectorsIndexed(vectorDB, testIndexName, 3);
219
+ }, 500000);
220
+
221
+ it.skip('should query vectors and return nearest neighbors', async () => {
222
+ const queryVector = [1.0, 0.1, 0.1];
223
+ const results = await vectorDB.query({ indexName: testIndexName, queryVector, topK: 3 });
224
+
225
+ expect(results).toHaveLength(3);
226
+ expect(results[0]!.score).toBeGreaterThan(0);
227
+ expect(results[0]!.metadata).toBeDefined();
228
+ }, 500000);
229
+
230
+ it('should query vectors with metadata filter', async () => {
231
+ const queryVector = [0.0, 1.0, 0.0];
232
+ const filter = { label: 'y-axis' };
233
+
234
+ const results = await vectorDB.query({ indexName: testIndexName, queryVector, topK: 1, filter });
235
+
236
+ expect(results).toHaveLength(1);
237
+ expect(results?.[0]?.metadata?.label).toBe('y-axis');
238
+ }, 500000);
239
+
240
+ it('should query vectors and return vectors in results', async () => {
241
+ const queryVector = [0.0, 1.0, 0.0];
242
+ const results = await vectorDB.query({ indexName: testIndexName, queryVector, topK: 1, includeVector: true });
243
+
244
+ expect(results).toHaveLength(1);
245
+ expect(results?.[0]?.vector).toBeDefined();
246
+ expect(results?.[0]?.vector).toHaveLength(dimension);
247
+ }, 500000);
248
+
249
+ describe('vector update operations', () => {
250
+ const testVectors = [
251
+ [1, 2, 3],
252
+ [4, 5, 6],
253
+ [7, 8, 9],
254
+ ];
255
+
256
+ beforeEach(async () => {
257
+ await vectorDB.createIndex({ indexName: indexNameUpdate, dimension, metric: 'cosine' });
258
+ await waitUntilReady(vectorDB, indexNameUpdate);
259
+ });
260
+
261
+ afterEach(async () => {
262
+ try {
263
+ await vectorDB.deleteIndex(indexNameUpdate);
264
+ await waitUntilIndexDeleted(vectorDB, indexNameUpdate);
265
+ } catch {
266
+ // Ignore errors if index doesn't exist
267
+ }
268
+ });
269
+
270
+ it('should update the vector by id', async () => {
271
+ const ids = await vectorDB.upsert({ indexName: indexNameUpdate, vectors: testVectors });
272
+ expect(ids).toHaveLength(3);
273
+
274
+ const idToBeUpdated = ids[0];
275
+ const newVector = [1, 2, 4];
276
+ const newMetaData = {
277
+ test: 'updates',
278
+ };
279
+
280
+ const update = {
281
+ vector: newVector,
282
+ metadata: newMetaData,
283
+ };
284
+
285
+ await vectorDB.updateIndexById(indexNameUpdate, idToBeUpdated, update);
286
+
287
+ await waitUntilVectorsIndexed(vectorDB, indexNameUpdate, 3);
288
+
289
+ const results: QueryResult[] = await vectorDB.query({
290
+ indexName: indexNameUpdate,
291
+ queryVector: newVector,
292
+ topK: 10,
293
+ includeVector: true,
294
+ });
295
+
296
+ expect(results[0]?.id).toBe(idToBeUpdated);
297
+ expect(results[0]?.vector).toEqual(newVector);
298
+ expect(results[0]?.metadata).toEqual(newMetaData);
299
+ }, 500000);
300
+
301
+ it('should only update the metadata by id', async () => {
302
+ const ids = await vectorDB.upsert({ indexName: indexNameUpdate, vectors: testVectors });
303
+ expect(ids).toHaveLength(3);
304
+
305
+ const idToBeUpdated = ids[0];
306
+ const newMetaData = {
307
+ test: 'updates',
308
+ };
309
+
310
+ const update = {
311
+ metadata: newMetaData,
312
+ };
313
+
314
+ await vectorDB.updateIndexById(indexNameUpdate, idToBeUpdated, update);
315
+
316
+ await waitUntilVectorsIndexed(vectorDB, indexNameUpdate, 3);
317
+
318
+ const results: QueryResult[] = await vectorDB.query({
319
+ indexName: indexNameUpdate,
320
+ queryVector: testVectors[0],
321
+ topK: 2,
322
+ includeVector: true,
323
+ });
324
+
325
+ expect(results[0]?.id).toBe(idToBeUpdated);
326
+ expect(results[0]?.vector).toEqual(testVectors[0]);
327
+ expect(results[0]?.metadata).toEqual(newMetaData);
328
+ }, 500000);
329
+
330
+ it('should only update vector embeddings by id', async () => {
331
+ const ids = await vectorDB.upsert({ indexName: indexNameUpdate, vectors: testVectors });
332
+ expect(ids).toHaveLength(3);
333
+
334
+ const idToBeUpdated = ids[0];
335
+ const newVector = [4, 4, 4];
336
+
337
+ const update = {
338
+ vector: newVector,
339
+ };
340
+
341
+ await vectorDB.updateIndexById(indexNameUpdate, idToBeUpdated, update);
342
+
343
+ await waitUntilVectorsIndexed(vectorDB, indexNameUpdate, 3);
344
+
345
+ const results: QueryResult[] = await vectorDB.query({
346
+ indexName: indexNameUpdate,
347
+ queryVector: newVector,
348
+ topK: 10,
349
+ includeVector: true,
350
+ });
351
+
352
+ const updatedResult = results.find(r => r.id === idToBeUpdated);
353
+ expect(updatedResult).toBeDefined();
354
+ expect(updatedResult?.vector).toEqual(newVector);
355
+ }, 500000);
356
+
357
+ it('should throw exception when no updates are given', async () => {
358
+ await expect(vectorDB.updateIndexById(indexNameUpdate, 'id', {})).rejects.toThrow('No updates provided');
359
+ });
360
+
361
+ it('should throw error for non-existent index', async () => {
362
+ const nonExistentIndex = 'non-existent-index';
363
+ await expect(vectorDB.updateIndexById(nonExistentIndex, 'test-id', { vector: [1, 2, 3] })).rejects.toThrow();
364
+ });
365
+
366
+ it('should throw error for invalid vector dimension', async () => {
367
+ const [id] = await vectorDB.upsert({
368
+ indexName: indexNameUpdate,
369
+ vectors: [[1, 2, 3]],
370
+ metadata: [{ test: 'initial' }],
371
+ });
372
+
373
+ await expect(
374
+ vectorDB.updateIndexById(indexNameUpdate, id, { vector: [1, 2] }), // Wrong dimension
375
+ ).rejects.toThrow();
376
+ }, 500000);
377
+ });
378
+
379
+ describe('vector delete operations', () => {
380
+ const testVectors = [
381
+ [1, 2, 3],
382
+ [4, 5, 6],
383
+ [7, 8, 9],
384
+ ];
385
+
386
+ beforeEach(async () => {
387
+ await vectorDB.createIndex({ indexName: indexNameDelete, dimension, metric: 'cosine' });
388
+ await waitUntilReady(vectorDB, indexNameDelete);
389
+ });
390
+
391
+ afterEach(async () => {
392
+ try {
393
+ await vectorDB.deleteIndex(indexNameDelete);
394
+ await waitUntilIndexDeleted(vectorDB, indexNameDelete);
395
+ } catch {
396
+ // Ignore errors if index doesn't exist
397
+ }
398
+ });
399
+
400
+ it('should delete the vector by id', async () => {
401
+ const ids = await vectorDB.upsert({ indexName: indexNameDelete, vectors: testVectors });
402
+ expect(ids).toHaveLength(3);
403
+ const idToBeDeleted = ids[0];
404
+
405
+ await vectorDB.deleteIndexById(indexNameDelete, idToBeDeleted);
406
+ await waitUntilVectorsIndexed(vectorDB, indexNameDelete, 2, true);
407
+
408
+ // Query all vectors similar to the deleted one
409
+ const results: QueryResult[] = await vectorDB.query({
410
+ indexName: indexNameDelete,
411
+ queryVector: testVectors[0],
412
+ topK: 3,
413
+ includeVector: true,
414
+ });
415
+
416
+ const resultIds = results.map(r => r.id);
417
+ expect(resultIds).not.toContain(idToBeDeleted);
418
+ }, 500000);
419
+ });
420
+ });
421
+
422
+ describe('Namespace Operations', () => {
423
+ const namespace1 = 'test-namespace-1';
424
+ const namespace2 = 'test-namespace-2';
425
+ const testVector = [1.0, 0.0, 0.0];
426
+ const testMetadata = { label: 'test' };
427
+
428
+ beforeEach(async () => {
429
+ await vectorDB.createIndex({ indexName: indexNameNamespace, dimension, metric: 'cosine' });
430
+ await waitUntilReady(vectorDB, indexNameNamespace);
431
+ });
432
+
433
+ afterEach(async () => {
434
+ try {
435
+ await vectorDB.deleteIndex(indexNameNamespace);
436
+ await waitUntilIndexDeleted(vectorDB, indexNameNamespace);
437
+ } catch {
438
+ // Ignore errors if index doesn't exist
439
+ }
440
+ });
441
+
442
+ it('should isolate vectors in different namespaces', async () => {
443
+ // Insert same vector in two namespaces
444
+ const [id1] = await vectorDB.upsert({
445
+ indexName: indexNameNamespace,
446
+ vectors: [testVector],
447
+ metadata: [testMetadata],
448
+ namespace: namespace1,
449
+ });
450
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 1);
451
+
452
+ const [id2] = await vectorDB.upsert({
453
+ indexName: indexNameNamespace,
454
+ vectors: [testVector],
455
+ metadata: [{ ...testMetadata, label: 'test2' }],
456
+ namespace: namespace2,
457
+ });
458
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 2);
459
+
460
+ // Query namespace1
461
+ const results1 = await vectorDB.query({
462
+ indexName: indexNameNamespace,
463
+ queryVector: testVector,
464
+ namespace: namespace1,
465
+ });
466
+
467
+ // Query namespace2
468
+ const results2 = await vectorDB.query({
469
+ indexName: indexNameNamespace,
470
+ queryVector: testVector,
471
+ namespace: namespace2,
472
+ });
473
+
474
+ // Verify isolation
475
+ expect(results1).toHaveLength(1);
476
+ expect(results2).toHaveLength(1);
477
+ expect(results1[0]?.id).toBe(id1);
478
+ expect(results1[0]?.metadata?.label).toBe('test');
479
+ expect(results2[0]?.id).toBe(id2);
480
+ expect(results2[0]?.metadata?.label).toBe('test2');
481
+ }, 500000);
482
+
483
+ it('should update vectors within specific namespace', async () => {
484
+ const [id] = await vectorDB.upsert({
485
+ indexName: indexNameNamespace,
486
+ vectors: [testVector],
487
+ metadata: [testMetadata],
488
+ namespace: namespace1,
489
+ });
490
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 1);
491
+
492
+ // Update in namespace1
493
+ await vectorDB.updateIndexById(indexNameNamespace, id, { metadata: { label: 'updated' } }, namespace1);
494
+
495
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 1);
496
+
497
+ // Query to verify update
498
+ const results = await vectorDB.query({
499
+ indexName: indexNameNamespace,
500
+ queryVector: testVector,
501
+ namespace: namespace1,
502
+ });
503
+
504
+ expect(results).toHaveLength(1);
505
+ expect(results[0]?.metadata?.label).toBe('updated');
506
+ }, 500000);
507
+
508
+ it('should delete vectors from specific namespace', async () => {
509
+ const [id] = await vectorDB.upsert({
510
+ indexName: indexNameNamespace,
511
+ vectors: [testVector],
512
+ metadata: [testMetadata],
513
+ namespace: namespace1,
514
+ });
515
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 1);
516
+
517
+ // Delete from namespace1
518
+ await vectorDB.deleteIndexById(indexNameNamespace, id, namespace1);
519
+
520
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 0, true);
521
+
522
+ // Query to verify deletion
523
+ const results = await vectorDB.query({
524
+ indexName: indexNameNamespace,
525
+ queryVector: testVector,
526
+ namespace: namespace1,
527
+ });
528
+
529
+ expect(results.length).toBe(0);
530
+ }, 500000);
531
+
532
+ it('should show namespace stats in describeIndex', async () => {
533
+ await vectorDB.upsert({
534
+ indexName: indexNameNamespace,
535
+ vectors: [testVector],
536
+ metadata: [testMetadata],
537
+ namespace: namespace1,
538
+ });
539
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 1);
540
+ await vectorDB.upsert({
541
+ indexName: indexNameNamespace,
542
+ vectors: [testVector],
543
+ metadata: [{ ...testMetadata, label: 'test2' }],
544
+ namespace: namespace2,
545
+ });
546
+ await waitUntilVectorsIndexed(vectorDB, indexNameNamespace, 2);
547
+
548
+ const stats = await vectorDB.describeIndex(indexNameNamespace);
549
+ expect(stats.namespaces).toBeDefined();
550
+ expect(stats.namespaces?.[namespace1]).toBeDefined();
551
+ expect(stats.namespaces?.[namespace2]).toBeDefined();
552
+ expect(stats.namespaces?.[namespace1].recordCount).toBe(1);
553
+ expect(stats.namespaces?.[namespace2].recordCount).toBe(1);
554
+ }, 500000);
555
+ });
556
+
557
+ describe('Error Handling', () => {
558
+ it('should handle non-existent index query gracefully', async () => {
559
+ const nonExistentIndex = 'non-existent-index';
560
+ await expect(vectorDB.query({ indexName: nonExistentIndex, queryVector: [1, 0, 0] })).rejects.toThrow();
561
+ }, 500000);
562
+
563
+ it('should handle incorrect dimension vectors', async () => {
564
+ const wrongDimVector = [[1, 0]]; // 2D vector for 3D index
565
+ await expect(vectorDB.upsert({ indexName: testIndexName, vectors: wrongDimVector })).rejects.toThrow();
566
+ }, 500000);
567
+ });
568
+
569
+ describe('Performance Tests', () => {
570
+ it('should handle batch upsert of 1000 vectors', async () => {
571
+ const batchSize = 1000;
572
+ const vectors = Array(batchSize)
573
+ .fill(null)
574
+ .map(() =>
575
+ Array(dimension)
576
+ .fill(null)
577
+ .map(() => Math.random()),
578
+ );
579
+ const metadata = vectors.map((_, i) => ({ id: i }));
580
+
581
+ const start = Date.now();
582
+ const ids = await vectorDB.upsert({ indexName: testIndexName, vectors, metadata });
583
+ const duration = Date.now() - start;
584
+
585
+ expect(ids).toHaveLength(batchSize);
586
+ console.log(`Batch upsert of ${batchSize} vectors took ${duration}ms`);
587
+ }, 300000); // 5 minute timeout
588
+
589
+ it('should perform multiple concurrent queries', async () => {
590
+ const queryVector = [1, 0, 0];
591
+ const numQueries = 10;
592
+
593
+ const start = Date.now();
594
+ const promises = Array(numQueries)
595
+ .fill(null)
596
+ .map(() => vectorDB.query({ indexName: testIndexName, queryVector }));
597
+
598
+ const results = await Promise.all(promises);
599
+ const duration = Date.now() - start;
600
+
601
+ expect(results).toHaveLength(numQueries);
602
+ console.log(`${numQueries} concurrent queries took ${duration}ms`);
603
+ }, 500000);
604
+ });
605
+
606
+ describe('Filter Validation in Queries', () => {
607
+ it('rejects queries with null values', async () => {
608
+ await expect(
609
+ vectorDB.query({ indexName: testIndexName, queryVector: [1, 0, 0], topK: 10, filter: { field: null } }),
610
+ ).rejects.toThrow();
611
+
612
+ await expect(
613
+ vectorDB.query({
614
+ indexName: testIndexName,
615
+ queryVector: [1, 0, 0],
616
+ filter: { other: { $eq: null } },
617
+ }),
618
+ ).rejects.toThrow('the $eq operator must be followed by a string, boolean or a number, got null instead');
619
+ });
620
+
621
+ it('rejects invalid array operator values', async () => {
622
+ // Test non-undefined values
623
+ const invalidValues = [123, 'string', true, { key: 'value' }, null];
624
+ for (const op of ['$in', '$nin']) {
625
+ for (const val of invalidValues) {
626
+ await expect(
627
+ vectorDB.query({
628
+ indexName: testIndexName,
629
+ queryVector: [1, 0, 0],
630
+ filter: { field: { [op]: val } },
631
+ }),
632
+ ).rejects.toThrow(`the ${op} operator must be followed by a list of strings or a list of numbers`);
633
+ }
634
+ }
635
+ });
636
+
637
+ it('validates comparison operators', async () => {
638
+ const numOps = ['$gt', '$gte', '$lt', '$lte'];
639
+ const invalidNumericValues = ['not-a-number', true, [], {}, null]; // Removed undefined
640
+ for (const op of numOps) {
641
+ for (const val of invalidNumericValues) {
642
+ await expect(
643
+ vectorDB.query({
644
+ indexName: testIndexName,
645
+ queryVector: [1, 0, 0],
646
+ filter: { field: { [op]: val } },
647
+ }),
648
+ ).rejects.toThrow(`the ${op} operator must be followed by a number`);
649
+ }
650
+ }
651
+ });
652
+
653
+ it('rejects multiple invalid values', async () => {
654
+ await expect(
655
+ vectorDB.query({
656
+ indexName: testIndexName,
657
+ queryVector: [1, 0, 0],
658
+ filter: { field1: { $in: 'not-array' }, field2: { $exists: 'not-boolean' }, field3: { $gt: 'not-number' } },
659
+ }),
660
+ ).rejects.toThrow();
661
+ });
662
+
663
+ it('rejects invalid array values', async () => {
664
+ await expect(
665
+ vectorDB.query({
666
+ indexName: testIndexName,
667
+ queryVector: [1, 0, 0],
668
+ filter: { field: { $in: [null] } },
669
+ }),
670
+ ).rejects.toThrow('the $in operator must be followed by a list of strings or a list of numbers');
671
+
672
+ await expect(
673
+ vectorDB.query({
674
+ indexName: testIndexName,
675
+ queryVector: [1, 0, 0],
676
+ filter: { field: { $in: [undefined] } },
677
+ }),
678
+ ).rejects.toThrow('the $in operator must be followed by a list of strings or a list of numbers');
679
+
680
+ await expect(
681
+ vectorDB.query({
682
+ indexName: testIndexName,
683
+ queryVector: [1, 0, 0],
684
+ filter: { field: { $all: 'not-an-array' } },
685
+ }),
686
+ ).rejects.toThrow('A non-empty array is required for the $all operator');
687
+ });
688
+
689
+ it('handles empty object filters', async () => {
690
+ // Test empty object at top level
691
+ await expect(
692
+ vectorDB.query({
693
+ indexName: testIndexName,
694
+ queryVector: [1, 0, 0],
695
+ filter: { field: { $eq: {} } },
696
+ }),
697
+ ).rejects.toThrow('the $eq operator must be followed by a string, boolean or a number, got {} instead');
698
+ });
699
+
700
+ it('handles empty/undefined filters by returning all results', async () => {
701
+ // Empty objects and undefined are ignored by Pinecone
702
+ // and will return all results without filtering
703
+ const noFilterCases = [{ field: {} }, { field: undefined }, { field: { $in: undefined } }];
704
+
705
+ for (const filter of noFilterCases) {
706
+ const results = await vectorDB.query({
707
+ indexName: testIndexName,
708
+ queryVector: [1, 0, 0],
709
+ filter,
710
+ });
711
+ expect(results.length).toBeGreaterThan(0);
712
+ }
713
+ });
714
+ it('handles empty object filters', async () => {
715
+ // Test empty object at top level
716
+ await expect(
717
+ vectorDB.query({
718
+ indexName: testIndexName,
719
+ queryVector: [1, 0, 0],
720
+ filter: {},
721
+ }),
722
+ ).rejects.toThrow('You must enter a `filter` object with at least one key-value pair.');
723
+ });
724
+ });
725
+
726
+ describe('Metadata Filter Tests', () => {
727
+ const testVectors = [
728
+ [1.0, 0.0, 0.0],
729
+ [0.0, 1.0, 0.0],
730
+ [0.0, 0.0, 1.0],
731
+ [0.5, 0.5, 0.0],
732
+ [0.3, 0.3, 0.3],
733
+ [0.8, 0.1, 0.1],
734
+ [0.1, 0.8, 0.1],
735
+ [0.1, 0.1, 0.8],
736
+ ];
737
+
738
+ const testMetadata = [
739
+ { category: 'electronics', price: 1000, tags: ['premium', 'new'], inStock: true, rating: 4.5 },
740
+ { category: 'books', price: 50, tags: ['bestseller'], inStock: true, rating: 4.8 },
741
+ { category: 'electronics', price: 500, tags: ['refurbished'], inStock: false, rating: 4.0 },
742
+ { category: 'clothing', price: 75, tags: ['summer', 'sale'], inStock: true, rating: 4.2 },
743
+ { category: 'books', price: 30, tags: ['paperback', 'sale'], inStock: true, rating: 4.1 },
744
+ { category: 'electronics', price: 800, tags: ['premium'], inStock: true, rating: 4.7 },
745
+ { category: 'clothing', price: 150, tags: ['premium', 'new'], inStock: false, rating: 4.4 },
746
+ { category: 'books', price: 25, tags: ['paperback', 'bestseller'], inStock: true, rating: 4.3 },
747
+ ];
748
+
749
+ beforeAll(async () => {
750
+ await vectorDB.upsert({ indexName: testIndexName, vectors: testVectors, metadata: testMetadata });
751
+ // Wait for vectors to be indexed
752
+ await waitUntilVectorsIndexed(vectorDB, testIndexName, testVectors.length);
753
+ }, 500000);
754
+
755
+ describe('Comparison Operators', () => {
756
+ it('should filter with implict $eq', async () => {
757
+ const results = await vectorDB.query({
758
+ indexName: testIndexName,
759
+ queryVector: [1, 0, 0],
760
+ filter: { category: 'electronics' },
761
+ });
762
+ expect(results.length).toBeGreaterThan(0);
763
+ results.forEach(result => {
764
+ expect(result.metadata?.category).toBe('electronics');
765
+ });
766
+ });
767
+ it('should filter with $eq operator', async () => {
768
+ const results = await vectorDB.query({
769
+ indexName: testIndexName,
770
+ queryVector: [1, 0, 0],
771
+ filter: { category: { $eq: 'electronics' } },
772
+ });
773
+ expect(results.length).toBeGreaterThan(0);
774
+ results.forEach(result => {
775
+ expect(result.metadata?.category).toBe('electronics');
776
+ });
777
+ });
778
+
779
+ it('should filter with $gt operator', async () => {
780
+ const results = await vectorDB.query({
781
+ indexName: testIndexName,
782
+ queryVector: [1, 0, 0],
783
+ filter: { price: { $gt: 500 } },
784
+ });
785
+ expect(results.length).toBeGreaterThan(0);
786
+ results.forEach(result => {
787
+ expect(Number(result.metadata?.price)).toBeGreaterThan(500);
788
+ });
789
+ });
790
+
791
+ it('should filter with $gte operator', async () => {
792
+ const results = await vectorDB.query({
793
+ indexName: testIndexName,
794
+ queryVector: [1, 0, 0],
795
+ filter: { price: { $gte: 500 } },
796
+ });
797
+ expect(results.length).toBeGreaterThan(0);
798
+ results.forEach(result => {
799
+ expect(Number(result.metadata?.price)).toBeGreaterThanOrEqual(500);
800
+ });
801
+ });
802
+
803
+ it('should filter with $lt operator', async () => {
804
+ const results = await vectorDB.query({
805
+ indexName: testIndexName,
806
+ queryVector: [1, 0, 0],
807
+ filter: { price: { $lt: 100 } },
808
+ });
809
+ expect(results.length).toBeGreaterThan(0);
810
+ results.forEach(result => {
811
+ expect(Number(result.metadata?.price)).toBeLessThan(100);
812
+ });
813
+ });
814
+
815
+ it('should filter with $lte operator', async () => {
816
+ const results = await vectorDB.query({
817
+ indexName: testIndexName,
818
+ queryVector: [1, 0, 0],
819
+ filter: { price: { $lte: 50 } },
820
+ });
821
+ expect(results.length).toBeGreaterThan(0);
822
+ results.forEach(result => {
823
+ expect(Number(result.metadata?.price)).toBeLessThanOrEqual(50);
824
+ });
825
+ });
826
+
827
+ it('should filter with $ne operator', async () => {
828
+ const results = await vectorDB.query({
829
+ indexName: testIndexName,
830
+ queryVector: [1, 0, 0],
831
+ filter: { category: { $ne: 'electronics' } },
832
+ });
833
+ expect(results.length).toBeGreaterThan(0);
834
+ results.forEach(result => {
835
+ expect(result.metadata?.category).not.toBe('electronics');
836
+ });
837
+ });
838
+
839
+ it('filters with $gte, $lt, $lte operators', async () => {
840
+ const results = await vectorDB.query({
841
+ indexName: testIndexName,
842
+ queryVector: [1, 0, 0],
843
+ filter: { price: { $gte: 25, $lte: 30 } },
844
+ });
845
+ expect(results.length).toBe(2);
846
+ results.forEach(result => {
847
+ expect(Number(result.metadata?.price)).toBeLessThanOrEqual(30);
848
+ expect(Number(result.metadata?.price)).toBeGreaterThanOrEqual(25);
849
+ });
850
+ });
851
+ });
852
+
853
+ describe('Array Operators', () => {
854
+ it('should filter with $in operator for strings', async () => {
855
+ const results = await vectorDB.query({
856
+ indexName: testIndexName,
857
+ queryVector: [1, 0, 0],
858
+ filter: { category: { $in: ['electronics', 'books'] } },
859
+ });
860
+ expect(results.length).toBeGreaterThan(0);
861
+ results.forEach(result => {
862
+ expect(['electronics', 'books']).toContain(result.metadata?.category);
863
+ });
864
+ });
865
+
866
+ it('should filter with $in operator for numbers', async () => {
867
+ const results = await vectorDB.query({
868
+ indexName: testIndexName,
869
+ queryVector: [1, 0, 0],
870
+ filter: { price: { $in: [50, 75, 1000] } },
871
+ });
872
+ expect(results.length).toBeGreaterThan(0);
873
+ results.forEach(result => {
874
+ expect([50, 75, 1000]).toContain(result.metadata?.price);
875
+ });
876
+ });
877
+
878
+ it('should filter with $nin operator', async () => {
879
+ const results = await vectorDB.query({
880
+ indexName: testIndexName,
881
+ queryVector: [1, 0, 0],
882
+ filter: { category: { $nin: ['electronics', 'books'] } },
883
+ });
884
+ expect(results.length).toBeGreaterThan(0);
885
+ results.forEach(result => {
886
+ expect(['electronics', 'books']).not.toContain(result.metadata?.category);
887
+ });
888
+ });
889
+
890
+ it('should filter with $all operator', async () => {
891
+ const results = await vectorDB.query({
892
+ indexName: testIndexName,
893
+ queryVector: [1, 0, 0],
894
+ filter: { tags: { $all: ['premium', 'new'] } },
895
+ });
896
+ expect(results.length).toBeGreaterThan(0);
897
+ results.forEach(result => {
898
+ expect(result.metadata?.tags).toContain('premium');
899
+ expect(result.metadata?.tags).toContain('new');
900
+ });
901
+ });
902
+ });
903
+
904
+ describe('Logical Operators', () => {
905
+ it('should filter with implict $and', async () => {
906
+ const results = await vectorDB.query({
907
+ indexName: testIndexName,
908
+ queryVector: [1, 0, 0],
909
+ filter: { category: 'electronics', price: { $gt: 700 }, inStock: true },
910
+ });
911
+ expect(results.length).toBeGreaterThan(0);
912
+ results.forEach(result => {
913
+ expect(result.metadata?.category).toBe('electronics');
914
+ expect(Number(result.metadata?.price)).toBeGreaterThan(700);
915
+ expect(result.metadata?.inStock).toBe(true);
916
+ });
917
+ });
918
+ it('should filter with $and operator', async () => {
919
+ const results = await vectorDB.query({
920
+ indexName: testIndexName,
921
+ queryVector: [1, 0, 0],
922
+ filter: { $and: [{ category: 'electronics' }, { price: { $gt: 700 } }, { inStock: true }] },
923
+ });
924
+ expect(results.length).toBeGreaterThan(0);
925
+ results.forEach(result => {
926
+ expect(result.metadata?.category).toBe('electronics');
927
+ expect(Number(result.metadata?.price)).toBeGreaterThan(700);
928
+ expect(result.metadata?.inStock).toBe(true);
929
+ });
930
+ });
931
+
932
+ it('should filter with $or operator', async () => {
933
+ const results = await vectorDB.query({
934
+ indexName: testIndexName,
935
+ queryVector: [1, 0, 0],
936
+ filter: { $or: [{ price: { $gt: 900 } }, { tags: { $all: ['bestseller'] } }] },
937
+ });
938
+ expect(results.length).toBeGreaterThan(0);
939
+ results.forEach(result => {
940
+ const condition1 = Number(result.metadata?.price) > 900;
941
+ const condition2 = result.metadata?.tags?.includes('bestseller');
942
+ expect(condition1 || condition2).toBe(true);
943
+ });
944
+ });
945
+
946
+ it('should handle nested logical operators', async () => {
947
+ const results = await vectorDB.query({
948
+ indexName: testIndexName,
949
+ queryVector: [1, 0, 0],
950
+ filter: {
951
+ $and: [
952
+ {
953
+ $or: [{ category: 'electronics' }, { category: 'books' }],
954
+ },
955
+ { price: { $lt: 100 } },
956
+ { inStock: true },
957
+ ],
958
+ },
959
+ });
960
+ expect(results.length).toBeGreaterThan(0);
961
+ results.forEach(result => {
962
+ expect(['electronics', 'books']).toContain(result.metadata?.category);
963
+ expect(Number(result.metadata?.price)).toBeLessThan(100);
964
+ expect(result.metadata?.inStock).toBe(true);
965
+ });
966
+ });
967
+ });
968
+
969
+ describe('Complex Filter Combinations', () => {
970
+ it('should combine comparison and array operators', async () => {
971
+ const results = await vectorDB.query({
972
+ indexName: testIndexName,
973
+ queryVector: [1, 0, 0],
974
+ filter: { $and: [{ price: { $gte: 500 } }, { tags: { $in: ['premium', 'refurbished'] } }] },
975
+ });
976
+ expect(results.length).toBeGreaterThan(0);
977
+ results.forEach(result => {
978
+ expect(Number(result.metadata?.price)).toBeGreaterThanOrEqual(500);
979
+ expect(result.metadata?.tags?.some(tag => ['premium', 'refurbished'].includes(tag))).toBe(true);
980
+ });
981
+ });
982
+
983
+ it('should handle multiple conditions on same field', async () => {
984
+ const results = await vectorDB.query({
985
+ indexName: testIndexName,
986
+ queryVector: [1, 0, 0],
987
+ filter: { $and: [{ price: { $gte: 30 } }, { price: { $lte: 800 } }] },
988
+ });
989
+ expect(results.length).toBeGreaterThan(0);
990
+ results.forEach(result => {
991
+ const price = Number(result.metadata?.price);
992
+ expect(price).toBeGreaterThanOrEqual(30);
993
+ expect(price).toBeLessThanOrEqual(800);
994
+ });
995
+ });
996
+
997
+ it('should handle complex nested conditions', async () => {
998
+ const results = await vectorDB.query({
999
+ indexName: testIndexName,
1000
+ queryVector: [1, 0, 0],
1001
+ filter: {
1002
+ $or: [
1003
+ {
1004
+ $and: [{ category: 'electronics' }, { price: { $gt: 700 } }, { tags: { $all: ['premium'] } }],
1005
+ },
1006
+ {
1007
+ $and: [{ category: 'books' }, { price: { $lt: 50 } }, { tags: { $in: ['paperback'] } }],
1008
+ },
1009
+ ],
1010
+ },
1011
+ });
1012
+ expect(results.length).toBeGreaterThan(0);
1013
+ results.forEach(result => {
1014
+ const isExpensiveElectronics =
1015
+ result.metadata?.category === 'electronics' &&
1016
+ Number(result.metadata?.price) > 700 &&
1017
+ result.metadata?.tags?.includes('premium');
1018
+
1019
+ const isCheapBook =
1020
+ result.metadata?.category === 'books' &&
1021
+ Number(result.metadata?.price) < 50 &&
1022
+ result.metadata?.tags?.includes('paperback');
1023
+
1024
+ expect(isExpensiveElectronics || isCheapBook).toBe(true);
1025
+ });
1026
+ });
1027
+
1028
+ it('combines existence checks with other operators', async () => {
1029
+ const results = await vectorDB.query({
1030
+ indexName: testIndexName,
1031
+ queryVector: [1, 0, 0],
1032
+ filter: { $and: [{ category: 'clothing' }, { optionalField: { $exists: false } }] },
1033
+ });
1034
+ expect(results.length).toBe(2);
1035
+ expect(results[0]!.metadata!.category).toBe('clothing');
1036
+ expect('optionalField' in results[0]!.metadata!).toBe(false);
1037
+ });
1038
+ });
1039
+
1040
+ describe('Edge Cases', () => {
1041
+ it('should handle numeric comparisons with decimals', async () => {
1042
+ const results = await vectorDB.query({
1043
+ indexName: testIndexName,
1044
+ queryVector: [1, 0, 0],
1045
+ filter: { rating: { $gt: 4.5 } },
1046
+ });
1047
+ expect(results.length).toBeGreaterThan(0);
1048
+ results.forEach(result => {
1049
+ expect(Number(result.metadata?.rating)).toBeGreaterThan(4.5);
1050
+ });
1051
+ });
1052
+
1053
+ it('should handle boolean values', async () => {
1054
+ const results = await vectorDB.query({
1055
+ indexName: testIndexName,
1056
+ queryVector: [1, 0, 0],
1057
+ filter: { inStock: { $eq: false } },
1058
+ });
1059
+ expect(results.length).toBeGreaterThan(0);
1060
+ results.forEach(result => {
1061
+ expect(result.metadata?.inStock).toBe(false);
1062
+ });
1063
+ });
1064
+
1065
+ it('should handle empty array in $in operator', async () => {
1066
+ const results = await vectorDB.query({
1067
+ indexName: testIndexName,
1068
+ queryVector: [1, 0, 0],
1069
+ filter: { category: { $in: [] } },
1070
+ });
1071
+ expect(results).toHaveLength(0);
1072
+ });
1073
+
1074
+ it('should handle single value in $all operator', async () => {
1075
+ const results = await vectorDB.query({
1076
+ indexName: testIndexName,
1077
+ queryVector: [1, 0, 0],
1078
+ filter: { tags: { $all: ['premium'] } },
1079
+ });
1080
+ expect(results.length).toBeGreaterThan(0);
1081
+ results.forEach(result => {
1082
+ expect(result.metadata?.tags).toContain('premium');
1083
+ });
1084
+ });
1085
+ });
1086
+ });
1087
+
1088
+ describe('Additional Validation Tests', () => {
1089
+ it('should reject non-numeric values in numeric comparisons', async () => {
1090
+ await expect(
1091
+ vectorDB.query({
1092
+ indexName: testIndexName,
1093
+ queryVector: [1, 0, 0],
1094
+ filter: { price: { $gt: '500' } }, // string instead of number
1095
+ }),
1096
+ ).rejects.toThrow('the $gt operator must be followed by a number');
1097
+ });
1098
+
1099
+ it('should reject invalid types in $in operator', async () => {
1100
+ await expect(
1101
+ vectorDB.query({
1102
+ indexName: testIndexName,
1103
+ queryVector: [1, 0, 0],
1104
+ filter: { price: { $in: [true, false] } }, // booleans instead of numbers
1105
+ }),
1106
+ ).rejects.toThrow('the $in operator must be followed by a list of strings or a list of numbers');
1107
+ });
1108
+
1109
+ it('should reject mixed types in $in operator', async () => {
1110
+ await expect(
1111
+ vectorDB.query({
1112
+ indexName: testIndexName,
1113
+ queryVector: [1, 0, 0],
1114
+ filter: { field: { $in: ['string', 123] } }, // mixed string and number
1115
+ }),
1116
+ ).rejects.toThrow();
1117
+ });
1118
+ it('should handle undefined filter', async () => {
1119
+ const results1 = await vectorDB.query({
1120
+ indexName: testIndexName,
1121
+ queryVector: [1, 0, 0],
1122
+ filter: undefined,
1123
+ });
1124
+ const results2 = await vectorDB.query({
1125
+ indexName: testIndexName,
1126
+ queryVector: [1, 0, 0],
1127
+ });
1128
+ expect(results1).toEqual(results2);
1129
+ expect(results1.length).toBeGreaterThan(0);
1130
+ });
1131
+
1132
+ it('should handle null filter', async () => {
1133
+ const results = await vectorDB.query({
1134
+ indexName: testIndexName,
1135
+ queryVector: [1, 0, 0],
1136
+ filter: null,
1137
+ });
1138
+ const results2 = await vectorDB.query({
1139
+ indexName: testIndexName,
1140
+ queryVector: [1, 0, 0],
1141
+ });
1142
+ expect(results).toEqual(results2);
1143
+ expect(results.length).toBeGreaterThan(0);
1144
+ });
1145
+ });
1146
+
1147
+ describe('Additional Edge Cases', () => {
1148
+ it('should handle exact boundary conditions', async () => {
1149
+ // Test exact boundary values from our test data
1150
+ const results = await vectorDB.query({
1151
+ indexName: testIndexName,
1152
+ queryVector: [1, 0, 0],
1153
+ filter: { $and: [{ price: { $gte: 25 } }, { price: { $lte: 1000 } }] },
1154
+ });
1155
+ expect(results.length).toBeGreaterThan(0);
1156
+ // Should include both boundary values
1157
+ expect(results.some(r => r.metadata?.price === 25)).toBe(true);
1158
+ expect(results.some(r => r.metadata?.price === 1000)).toBe(true);
1159
+ });
1160
+
1161
+ it('should handle multiple $all conditions on same array field', async () => {
1162
+ const results = await vectorDB.query({
1163
+ indexName: testIndexName,
1164
+ queryVector: [1, 0, 0],
1165
+ filter: { $and: [{ tags: { $all: ['premium'] } }, { tags: { $all: ['new'] } }] },
1166
+ });
1167
+ expect(results.length).toBeGreaterThan(0);
1168
+ results.forEach(result => {
1169
+ expect(result.metadata?.tags).toContain('premium');
1170
+ expect(result.metadata?.tags).toContain('new');
1171
+ });
1172
+ });
1173
+
1174
+ it('should handle multiple array operator combinations', async () => {
1175
+ const results = await vectorDB.query({
1176
+ indexName: testIndexName,
1177
+ queryVector: [1, 0, 0],
1178
+ filter: { $and: [{ tags: { $all: ['premium'] } }, { tags: { $in: ['new', 'refurbished'] } }] },
1179
+ });
1180
+ expect(results.length).toBeGreaterThan(0);
1181
+ results.forEach(result => {
1182
+ expect(result.metadata?.tags).toContain('premium');
1183
+ expect(result.metadata?.tags?.some(tag => ['new', 'refurbished'].includes(tag))).toBe(true);
1184
+ });
1185
+ });
1186
+ });
1187
+
1188
+ describe('Additional Complex Logical Combinations', () => {
1189
+ it('should handle deeply nested $or conditions', async () => {
1190
+ const results = await vectorDB.query({
1191
+ indexName: testIndexName,
1192
+ queryVector: [1, 0, 0],
1193
+ filter: {
1194
+ $or: [
1195
+ {
1196
+ $and: [{ category: 'electronics' }, { $or: [{ price: { $gt: 900 } }, { tags: { $all: ['premium'] } }] }],
1197
+ },
1198
+ {
1199
+ $and: [{ category: 'books' }, { $or: [{ price: { $lt: 30 } }, { tags: { $all: ['bestseller'] } }] }],
1200
+ },
1201
+ ],
1202
+ },
1203
+ });
1204
+ expect(results.length).toBeGreaterThan(0);
1205
+ results.forEach(result => {
1206
+ if (result.metadata?.category === 'electronics') {
1207
+ expect(Number(result.metadata?.price) > 900 || result.metadata?.tags?.includes('premium')).toBe(true);
1208
+ } else if (result.metadata?.category === 'books') {
1209
+ expect(Number(result.metadata?.price) < 30 || result.metadata?.tags?.includes('bestseller')).toBe(true);
1210
+ }
1211
+ });
1212
+ });
1213
+
1214
+ it('should handle multiple field comparisons with same value', async () => {
1215
+ const results = await vectorDB.query({
1216
+ indexName: testIndexName,
1217
+ queryVector: [1, 0, 0],
1218
+ filter: { $or: [{ price: { $gt: 500 } }, { rating: { $gt: 4.5 } }] },
1219
+ });
1220
+ expect(results.length).toBeGreaterThan(0);
1221
+ results.forEach(result => {
1222
+ expect(Number(result.metadata?.price) > 500 || Number(result.metadata?.rating) > 4.5).toBe(true);
1223
+ });
1224
+ });
1225
+
1226
+ it('should handle combination of array and numeric comparisons', async () => {
1227
+ const results = await vectorDB.query({
1228
+ indexName: testIndexName,
1229
+ queryVector: [1, 0, 0],
1230
+ filter: {
1231
+ $and: [
1232
+ { tags: { $in: ['premium', 'bestseller'] } },
1233
+ { $or: [{ price: { $gt: 500 } }, { rating: { $gt: 4.5 } }] },
1234
+ ],
1235
+ },
1236
+ });
1237
+ expect(results.length).toBeGreaterThan(0);
1238
+ results.forEach(result => {
1239
+ expect(['premium', 'bestseller'].some(tag => result.metadata?.tags?.includes(tag))).toBe(true);
1240
+ expect(Number(result.metadata?.price) > 500 || Number(result.metadata?.rating) > 4.5).toBe(true);
1241
+ });
1242
+ });
1243
+ });
1244
+
1245
+ describe('Performance Edge Cases', () => {
1246
+ it('should handle filters with many conditions', async () => {
1247
+ const results = await vectorDB.query({
1248
+ indexName: testIndexName,
1249
+ queryVector: [1, 0, 0],
1250
+ filter: {
1251
+ $and: Array(10)
1252
+ .fill(null)
1253
+ .map(() => ({
1254
+ $or: [{ price: { $gt: 100 } }, { rating: { $gt: 4.0 } }],
1255
+ })),
1256
+ },
1257
+ });
1258
+ expect(results.length).toBeGreaterThan(0);
1259
+ results.forEach(result => {
1260
+ expect(Number(result.metadata?.price) > 100 || Number(result.metadata?.rating) > 4.0).toBe(true);
1261
+ });
1262
+ });
1263
+
1264
+ it('should handle deeply nested conditions efficiently', async () => {
1265
+ const results = await vectorDB.query({
1266
+ indexName: testIndexName,
1267
+ queryVector: [1, 0, 0],
1268
+ filter: {
1269
+ $or: Array(5)
1270
+ .fill(null)
1271
+ .map(() => ({
1272
+ $and: [{ category: { $in: ['electronics', 'books'] } }, { price: { $gt: 50 } }, { rating: { $gt: 4.0 } }],
1273
+ })),
1274
+ },
1275
+ });
1276
+ expect(results.length).toBeGreaterThan(0);
1277
+ results.forEach(result => {
1278
+ expect(['electronics', 'books']).toContain(result.metadata?.category);
1279
+ expect(Number(result.metadata?.price)).toBeGreaterThan(50);
1280
+ expect(Number(result.metadata?.rating)).toBeGreaterThan(4.0);
1281
+ });
1282
+ });
1283
+
1284
+ it('should handle large number of $or conditions', async () => {
1285
+ const results = await vectorDB.query({
1286
+ indexName: testIndexName,
1287
+ queryVector: [1, 0, 0],
1288
+ filter: {
1289
+ $or: [
1290
+ ...Array(5)
1291
+ .fill(null)
1292
+ .map((_, i) => ({
1293
+ price: { $gt: i * 100 },
1294
+ })),
1295
+ ...Array(5)
1296
+ .fill(null)
1297
+ .map((_, i) => ({
1298
+ rating: { $gt: 4.0 + i * 0.1 },
1299
+ })),
1300
+ ],
1301
+ },
1302
+ });
1303
+ expect(results.length).toBeGreaterThan(0);
1304
+ });
1305
+ });
1306
+
1307
+ describe('Hybrid Search Operations', () => {
1308
+ const testVectors = [
1309
+ [0.9, 0.1, 0.0], // cats (very distinct)
1310
+ [0.1, 0.9, 0.0], // dogs (very distinct)
1311
+ [0.0, 0.0, 0.9], // birds (completely different)
1312
+ ];
1313
+
1314
+ const testMetadata = [
1315
+ { text: 'cats purr and meow', animal: 'cat' },
1316
+ { text: 'dogs bark and fetch', animal: 'dog' },
1317
+ { text: 'birds fly and nest', animal: 'bird' },
1318
+ ];
1319
+
1320
+ // Create sparse vectors with fixed vocabulary indices
1321
+ const testSparseVectors = [
1322
+ { indices: [0], values: [1.0] }, // cat terms only
1323
+ { indices: [1], values: [1.0] }, // dog terms only
1324
+ { indices: [2], values: [1.0] }, // bird terms only
1325
+ ];
1326
+
1327
+ beforeEach(async () => {
1328
+ await vectorDB.createIndex({ indexName: indexNameHybrid, dimension: 3, metric: 'dotproduct' });
1329
+ await waitUntilReady(vectorDB, indexNameHybrid);
1330
+
1331
+ // Upsert with both dense and sparse vectors
1332
+ await vectorDB.upsert({
1333
+ indexName: indexNameHybrid,
1334
+ vectors: testVectors,
1335
+ sparseVectors: testSparseVectors,
1336
+ metadata: testMetadata,
1337
+ });
1338
+ await waitUntilVectorsIndexed(vectorDB, indexNameHybrid, 3);
1339
+ });
1340
+
1341
+ afterEach(async () => {
1342
+ try {
1343
+ await vectorDB.deleteIndex(indexNameHybrid);
1344
+ await waitUntilIndexDeleted(vectorDB, indexNameHybrid);
1345
+ } catch {
1346
+ // Ignore errors if index doesn't exist
1347
+ }
1348
+ });
1349
+
1350
+ it('should combine dense and sparse signals in hybrid search', async () => {
1351
+ // Query vector strongly favors cats
1352
+ const queryVector = [1.0, 0.0, 0.0];
1353
+ // But sparse vector strongly favors dogs
1354
+ const sparseVector = {
1355
+ indices: [1], // Index 1 corresponds to dog-related terms
1356
+ values: [1.0], // Maximum weight for dog terms
1357
+ };
1358
+
1359
+ const results = await vectorDB.query({
1360
+ indexName: indexNameHybrid,
1361
+ queryVector,
1362
+ sparseVector,
1363
+ topK: 2,
1364
+ });
1365
+
1366
+ expect(results).toHaveLength(2);
1367
+
1368
+ // Get results with just vector similarity
1369
+ const vectorResults = await vectorDB.query({
1370
+ indexName: indexNameHybrid,
1371
+ queryVector,
1372
+ topK: 2,
1373
+ });
1374
+
1375
+ // Results should be different when using hybrid search vs just vector
1376
+ expect(results[0].id).not.toBe(vectorResults[0].id);
1377
+
1378
+ // First result should be dog due to sparse vector influence
1379
+ expect(results[0].metadata?.animal).toBe('dog');
1380
+ });
1381
+
1382
+ it('should support sparse vectors as optional parameters', async () => {
1383
+ // Should work with just dense vectors in upsert
1384
+ await vectorDB.upsert({
1385
+ indexName: indexNameHybrid,
1386
+ vectors: [[0.1, 0.2, 0.3]],
1387
+ metadata: [{ test: 'dense only' }],
1388
+ });
1389
+
1390
+ // Should work with just dense vector in query
1391
+ const denseOnlyResults = await vectorDB.query({
1392
+ indexName: indexNameHybrid,
1393
+ queryVector: [0.1, 0.2, 0.3],
1394
+ topK: 1,
1395
+ });
1396
+ expect(denseOnlyResults).toHaveLength(1);
1397
+
1398
+ // Should work with both dense and sparse in query
1399
+ const hybridResults = await vectorDB.query({
1400
+ indexName: indexNameHybrid,
1401
+ queryVector: [0.1, 0.2, 0.3],
1402
+ sparseVector: createSparseVector('test query'),
1403
+ topK: 1,
1404
+ });
1405
+ expect(hybridResults).toHaveLength(1);
1406
+ });
1407
+ });
1408
+
1409
+ describe('Deprecation Warnings', () => {
1410
+ const indexName = 'testdeprecationwarnings';
1411
+
1412
+ const indexName2 = 'testdeprecationwarnings2';
1413
+
1414
+ const indexName3 = 'testdeprecationwarnings3';
1415
+
1416
+ const indexName4 = 'testdeprecationwarnings4';
1417
+
1418
+ let warnSpy;
1419
+
1420
+ beforeAll(async () => {
1421
+ try {
1422
+ await vectorDB.deleteIndex(indexName);
1423
+ } catch {
1424
+ // Ignore errors if index doesn't exist
1425
+ }
1426
+ try {
1427
+ await vectorDB.deleteIndex(indexName2);
1428
+ } catch {
1429
+ // Ignore errors if index doesn't exist
1430
+ }
1431
+ try {
1432
+ await vectorDB.deleteIndex(indexName3);
1433
+ } catch {
1434
+ // Ignore errors if index doesn't exist
1435
+ }
1436
+ try {
1437
+ await vectorDB.deleteIndex(indexName4);
1438
+ } catch {
1439
+ // Ignore errors if index doesn't exist
1440
+ }
1441
+ await vectorDB.createIndex({ indexName: indexName, dimension: 3 });
1442
+ await waitUntilReady(vectorDB, indexName);
1443
+ });
1444
+
1445
+ afterAll(async () => {
1446
+ try {
1447
+ await vectorDB.deleteIndex(indexName);
1448
+ } catch {
1449
+ // Ignore errors if index doesn't exist
1450
+ }
1451
+ try {
1452
+ await vectorDB.deleteIndex(indexName2);
1453
+ } catch {
1454
+ // Ignore errors if index doesn't exist
1455
+ }
1456
+ try {
1457
+ await vectorDB.deleteIndex(indexName3);
1458
+ } catch {
1459
+ // Ignore errors if index doesn't exist
1460
+ }
1461
+ try {
1462
+ await vectorDB.deleteIndex(indexName4);
1463
+ } catch {
1464
+ // Ignore errors if index doesn't exist
1465
+ }
1466
+ });
1467
+
1468
+ beforeEach(async () => {
1469
+ warnSpy = vi.spyOn(vectorDB['logger'], 'warn');
1470
+ });
1471
+
1472
+ afterEach(async () => {
1473
+ warnSpy.mockRestore();
1474
+ });
1475
+
1476
+ it('should show deprecation warning when using individual args for createIndex', async () => {
1477
+ await vectorDB.createIndex(indexName2, 3, 'cosine');
1478
+ await waitUntilReady(vectorDB, indexName2);
1479
+ expect(warnSpy).toHaveBeenCalledWith(
1480
+ expect.stringContaining('Deprecation Warning: Passing individual arguments to createIndex() is deprecated'),
1481
+ );
1482
+ });
1483
+
1484
+ it('should show deprecation warning when using individual args for upsert', async () => {
1485
+ await vectorDB.upsert(indexName, [[1, 2, 3]], [{ test: 'data' }]);
1486
+
1487
+ expect(warnSpy).toHaveBeenCalledWith(
1488
+ expect.stringContaining('Deprecation Warning: Passing individual arguments to upsert() is deprecated'),
1489
+ );
1490
+ });
1491
+
1492
+ it('should show deprecation warning when using individual args for query', async () => {
1493
+ await vectorDB.query(indexName, [1, 2, 3], 5);
1494
+
1495
+ expect(warnSpy).toHaveBeenCalledWith(
1496
+ expect.stringContaining('Deprecation Warning: Passing individual arguments to query() is deprecated'),
1497
+ );
1498
+ });
1499
+
1500
+ it('should not show deprecation warning when using object param for query', async () => {
1501
+ await vectorDB.query({
1502
+ indexName,
1503
+ queryVector: [1, 2, 3],
1504
+ topK: 5,
1505
+ });
1506
+
1507
+ expect(warnSpy).not.toHaveBeenCalled();
1508
+ });
1509
+
1510
+ it('should not show deprecation warning when using object param for createIndex', async () => {
1511
+ await vectorDB.createIndex({
1512
+ indexName: indexName3,
1513
+ dimension: 3,
1514
+ metric: 'cosine',
1515
+ });
1516
+
1517
+ expect(warnSpy).not.toHaveBeenCalled();
1518
+ });
1519
+
1520
+ it('should not show deprecation warning when using object param for upsert', async () => {
1521
+ await vectorDB.upsert({
1522
+ indexName,
1523
+ vectors: [[1, 2, 3]],
1524
+ metadata: [{ test: 'data' }],
1525
+ });
1526
+
1527
+ expect(warnSpy).not.toHaveBeenCalled();
1528
+ });
1529
+
1530
+ it('should maintain backward compatibility with individual args', async () => {
1531
+ // Query
1532
+ const queryResults = await vectorDB.query(indexName, [1, 2, 3], 5);
1533
+ expect(Array.isArray(queryResults)).toBe(true);
1534
+
1535
+ // CreateIndex
1536
+ await expect(vectorDB.createIndex(indexName4, 3, 'cosine')).resolves.not.toThrow();
1537
+ await waitUntilReady(vectorDB, indexName4);
1538
+ // Upsert
1539
+ const upsertResults = await vectorDB.upsert({
1540
+ indexName,
1541
+ vectors: [[1, 2, 3]],
1542
+ metadata: [{ test: 'data' }],
1543
+ });
1544
+ expect(Array.isArray(upsertResults)).toBe(true);
1545
+ expect(upsertResults).toHaveLength(1);
1546
+ });
1547
+ });
1548
+ });