@mastra/memory 1.0.0-beta.9 → 1.0.0

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,942 @@
1
+ # Vectors API Reference
2
+
3
+ > API reference for vectors - 4 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: libSQL Vector Store
9
+
10
+ > Documentation for the LibSQLVector class in Mastra, which provides vector search using libSQL with vector extensions.
11
+
12
+ The libSQL storage implementation provides a SQLite-compatible vector search [libSQL](https://github.com/tursodatabase/libsql), a fork of SQLite with vector extensions, and [Turso](https://turso.tech/) with vector extensions, offering a lightweight and efficient vector database solution.
13
+ It's part of the `@mastra/libsql` package and offers efficient vector similarity search with metadata filtering.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @mastra/libsql@beta
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```typescript
24
+ import { LibSQLVector } from "@mastra/libsql";
25
+
26
+ // Create a new vector store instance
27
+ const store = new LibSQLVector({
28
+ id: 'libsql-vector',
29
+ url: process.env.DATABASE_URL,
30
+ // Optional: for Turso cloud databases
31
+ authToken: process.env.DATABASE_AUTH_TOKEN,
32
+ });
33
+
34
+ // Create an index
35
+ await store.createIndex({
36
+ indexName: "myCollection",
37
+ dimension: 1536,
38
+ });
39
+
40
+ // Add vectors with metadata
41
+ const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]];
42
+ const metadata = [
43
+ { text: "first document", category: "A" },
44
+ { text: "second document", category: "B" }
45
+ ];
46
+ await store.upsert({
47
+ indexName: "myCollection",
48
+ vectors,
49
+ metadata,
50
+ });
51
+
52
+ // Query similar vectors
53
+ const queryVector = [0.1, 0.2, ...];
54
+ const results = await store.query({
55
+ indexName: "myCollection",
56
+ queryVector,
57
+ topK: 10, // top K results
58
+ filter: { category: "A" } // optional metadata filter
59
+ });
60
+ ```
61
+
62
+ ## Constructor Options
63
+
64
+ ## Methods
65
+
66
+ ### createIndex()
67
+
68
+ Creates a new vector collection. The index name must start with a letter or underscore and can only contain letters, numbers, and underscores. The dimension must be a positive integer.
69
+
70
+ ### upsert()
71
+
72
+ Adds or updates vectors and their metadata in the index. Uses a transaction to ensure all vectors are inserted atomically - if any insert fails, the entire operation is rolled back.
73
+
74
+ ### query()
75
+
76
+ Searches for similar vectors with optional metadata filtering.
77
+
78
+ ### describeIndex()
79
+
80
+ Gets information about an index.
81
+
82
+ Returns:
83
+
84
+ ```typescript
85
+ interface IndexStats {
86
+ dimension: number;
87
+ count: number;
88
+ metric: "cosine" | "euclidean" | "dotproduct";
89
+ }
90
+ ```
91
+
92
+ ### deleteIndex()
93
+
94
+ Deletes an index and all its data.
95
+
96
+ ### listIndexes()
97
+
98
+ Lists all vector indexes in the database.
99
+
100
+ Returns: `Promise<string[]>`
101
+
102
+ ### truncateIndex()
103
+
104
+ Removes all vectors from an index while keeping the index structure.
105
+
106
+ ### updateVector()
107
+
108
+ Update a single vector by ID or by metadata filter. Either `id` or `filter` must be provided, but not both.
109
+
110
+ ### deleteVector()
111
+
112
+ Deletes a specific vector entry from an index by its ID.
113
+
114
+ ### deleteVectors()
115
+
116
+ Delete multiple vectors by IDs or by metadata filter. Either `ids` or `filter` must be provided, but not both.
117
+
118
+ ## Response Types
119
+
120
+ Query results are returned in this format:
121
+
122
+ ```typescript
123
+ interface QueryResult {
124
+ id: string;
125
+ score: number;
126
+ metadata: Record<string, any>;
127
+ vector?: number[]; // Only included if includeVector is true
128
+ }
129
+ ```
130
+
131
+ ## Error Handling
132
+
133
+ The store throws specific errors for different failure cases:
134
+
135
+ ```typescript
136
+ try {
137
+ await store.query({
138
+ indexName: "my-collection",
139
+ queryVector: queryVector,
140
+ });
141
+ } catch (error) {
142
+ // Handle specific error cases
143
+ if (error.message.includes("Invalid index name format")) {
144
+ console.error(
145
+ "Index name must start with a letter/underscore and contain only alphanumeric characters",
146
+ );
147
+ } else if (error.message.includes("Table not found")) {
148
+ console.error("The specified index does not exist");
149
+ } else {
150
+ console.error("Vector store error:", error.message);
151
+ }
152
+ }
153
+ ```
154
+
155
+ Common error cases include:
156
+
157
+ - Invalid index name format
158
+ - Invalid vector dimensions
159
+ - Table/index not found
160
+ - Database connection issues
161
+ - Transaction failures during upsert
162
+
163
+ ## Usage Example
164
+
165
+ ### Local embeddings with fastembed
166
+
167
+ Embeddings are numeric vectors used by memory's `semanticRecall` to retrieve related messages by meaning (not keywords). This setup uses `@mastra/fastembed` to generate vector embeddings.
168
+
169
+ Install `fastembed` to get started:
170
+
171
+ ```bash
172
+ npm install @mastra/fastembed@beta
173
+ ```
174
+
175
+ Add the following to your agent:
176
+
177
+ ```typescript title="src/mastra/agents/example-libsql-agent.ts"
178
+ import { Memory } from "@mastra/memory";
179
+ import { Agent } from "@mastra/core/agent";
180
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
181
+ import { fastembed } from "@mastra/fastembed";
182
+
183
+ export const libsqlAgent = new Agent({
184
+ id: "libsql-agent",
185
+ name: "libSQL Agent",
186
+ instructions:
187
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
188
+ model: "openai/gpt-5.1",
189
+ memory: new Memory({
190
+ storage: new LibSQLStore({
191
+ id: 'libsql-agent-storage',
192
+ url: "file:libsql-agent.db",
193
+ }),
194
+ vector: new LibSQLVector({
195
+ id: 'libsql-agent-vector',
196
+ url: "file:libsql-agent.db",
197
+ }),
198
+ embedder: fastembed,
199
+ options: {
200
+ lastMessages: 10,
201
+ semanticRecall: {
202
+ topK: 3,
203
+ messageRange: 2,
204
+ },
205
+ generateTitle: true, // Explicitly enable automatic title generation
206
+ },
207
+ }),
208
+ });
209
+ ```
210
+
211
+ ## Related
212
+
213
+ - [Metadata Filters](../rag/metadata-filters)
214
+
215
+ ---
216
+
217
+ ## Reference: MongoDB Vector Store
218
+
219
+ > Documentation for the MongoDBVector class in Mastra, which provides vector search using MongoDB Atlas and Atlas Vector Search.
220
+
221
+ The `MongoDBVector` class provides vector search using [MongoDB Atlas Vector Search](https://www.mongodb.com/docs/atlas/atlas-vector-search/). It enables efficient similarity search and metadata filtering within your MongoDB collections.
222
+
223
+ ## Installation
224
+
225
+ ```bash
226
+ npm install @mastra/mongodb@beta
227
+ ```
228
+
229
+ ## Usage Example
230
+
231
+ ```typescript
232
+ import { MongoDBVector } from "@mastra/mongodb";
233
+
234
+ const store = new MongoDBVector({
235
+ id: 'mongodb-vector',
236
+ uri: process.env.MONGODB_URI,
237
+ dbName: process.env.MONGODB_DATABASE,
238
+ });
239
+ ```
240
+
241
+ ### Custom Embedding Field Path
242
+
243
+ If you need to store embeddings in a nested field structure (e.g., to integrate with existing MongoDB collections), use the `embeddingFieldPath` option:
244
+
245
+ ```typescript
246
+ import { MongoDBVector } from "@mastra/mongodb";
247
+
248
+ const store = new MongoDBVector({
249
+ id: 'mongodb-vector',
250
+ uri: process.env.MONGODB_URI,
251
+ dbName: process.env.MONGODB_DATABASE,
252
+ embeddingFieldPath: 'text.contentEmbedding', // Store embeddings at text.contentEmbedding
253
+ });
254
+ ```
255
+
256
+ ## Constructor Options
257
+
258
+ ## Methods
259
+
260
+ ### createIndex()
261
+
262
+ Creates a new vector index (collection) in MongoDB.
263
+
264
+ ### upsert()
265
+
266
+ Adds or updates vectors and their metadata in the collection.
267
+
268
+ ### query()
269
+
270
+ Searches for similar vectors with optional metadata filtering.
271
+
272
+ ### describeIndex()
273
+
274
+ Returns information about the index (collection).
275
+
276
+ Returns:
277
+
278
+ ```typescript
279
+ interface IndexStats {
280
+ dimension: number;
281
+ count: number;
282
+ metric: "cosine" | "euclidean" | "dotproduct";
283
+ }
284
+ ```
285
+
286
+ ### deleteIndex()
287
+
288
+ Deletes a collection and all its data.
289
+
290
+ ### listIndexes()
291
+
292
+ Lists all vector collections in the MongoDB database.
293
+
294
+ Returns: `Promise<string[]>`
295
+
296
+ ### updateVector()
297
+
298
+ Update a single vector by ID or by metadata filter. Either `id` or `filter` must be provided, but not both.
299
+
300
+ ### deleteVector()
301
+
302
+ Deletes a specific vector entry from an index by its ID.
303
+
304
+ ### deleteVectors()
305
+
306
+ Delete multiple vectors by IDs or by metadata filter. Either `ids` or `filter` must be provided, but not both.
307
+
308
+ ### disconnect()
309
+
310
+ Closes the MongoDB client connection. Should be called when done using the store.
311
+
312
+ ## Response Types
313
+
314
+ Query results are returned in this format:
315
+
316
+ ```typescript
317
+ interface QueryResult {
318
+ id: string;
319
+ score: number;
320
+ metadata: Record<string, any>;
321
+ vector?: number[]; // Only included if includeVector is true
322
+ }
323
+ ```
324
+
325
+ ## Error Handling
326
+
327
+ The store throws typed errors that can be caught:
328
+
329
+ ```typescript
330
+ try {
331
+ await store.query({
332
+ indexName: "my_collection",
333
+ queryVector: queryVector,
334
+ });
335
+ } catch (error) {
336
+ // Handle specific error cases
337
+ if (error.message.includes("Invalid collection name")) {
338
+ console.error(
339
+ "Collection name must start with a letter or underscore and contain only valid characters.",
340
+ );
341
+ } else if (error.message.includes("Collection not found")) {
342
+ console.error("The specified collection does not exist");
343
+ } else {
344
+ console.error("Vector store error:", error.message);
345
+ }
346
+ }
347
+ ```
348
+
349
+ ## Best Practices
350
+
351
+ - Index metadata fields used in filters for optimal query performance.
352
+ - Use consistent field naming in metadata to avoid unexpected query results.
353
+ - Regularly monitor index and collection statistics to ensure efficient search.
354
+
355
+ ## Usage Example
356
+
357
+ ### Vector embeddings with MongoDB
358
+
359
+ Embeddings are numeric vectors used by memory's `semanticRecall` to retrieve related messages by meaning (not keywords).
360
+
361
+ > Note: You must use a deployment hosted on MongoDB Atlas to successfully use the MongoDB Vector database.
362
+
363
+ This setup uses FastEmbed, a local embedding model, to generate vector embeddings.
364
+ To use this, install `@mastra/fastembed`:
365
+
366
+ ```bash
367
+ npm install @mastra/fastembed@beta
368
+ ```
369
+
370
+ Add the following to your agent:
371
+
372
+ ```typescript title="src/mastra/agents/example-mongodb-agent.ts"
373
+ import { Memory } from "@mastra/memory";
374
+ import { Agent } from "@mastra/core/agent";
375
+ import { MongoDBStore, MongoDBVector } from "@mastra/mongodb";
376
+ import { fastembed } from "@mastra/fastembed";
377
+
378
+ export const mongodbAgent = new Agent({
379
+ id: "mongodb-agent",
380
+ name: "mongodb-agent",
381
+ instructions:
382
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
383
+ model: "openai/gpt-5.1",
384
+ memory: new Memory({
385
+ storage: new MongoDBStore({
386
+ id: 'mongodb-storage',
387
+ uri: process.env.MONGODB_URI!,
388
+ dbName: process.env.MONGODB_DB_NAME!,
389
+ }),
390
+ vector: new MongoDBVector({
391
+ id: 'mongodb-vector',
392
+ uri: process.env.MONGODB_URI!,
393
+ dbName: process.env.MONGODB_DB_NAME!,
394
+ }),
395
+ embedder: fastembed,
396
+ options: {
397
+ lastMessages: 10,
398
+ semanticRecall: {
399
+ topK: 3,
400
+ messageRange: 2,
401
+ },
402
+ generateTitle: true, // generates descriptive thread titles automatically
403
+ },
404
+ }),
405
+ });
406
+ ```
407
+
408
+ ## Related
409
+
410
+ - [Metadata Filters](../rag/metadata-filters)
411
+
412
+ ---
413
+
414
+ ## Reference: PG Vector Store
415
+
416
+ > Documentation for the PgVector class in Mastra, which provides vector search using PostgreSQL with pgvector extension.
417
+
418
+ The PgVector class provides vector search using [PostgreSQL](https://www.postgresql.org/) with [pgvector](https://github.com/pgvector/pgvector) extension.
419
+ It provides robust vector similarity search capabilities within your existing PostgreSQL database.
420
+
421
+ ## Constructor Options
422
+
423
+ ## Constructor Examples
424
+
425
+ ### Connection String
426
+
427
+ ```ts
428
+ import { PgVector } from "@mastra/pg";
429
+
430
+ const vectorStore = new PgVector({
431
+ id: 'pg-vector',
432
+ connectionString: "postgresql://user:password@localhost:5432/mydb",
433
+ });
434
+ ```
435
+
436
+ ### Host/Port/Database Configuration
437
+
438
+ ```ts
439
+ const vectorStore = new PgVector({
440
+ id: 'pg-vector',
441
+ host: "localhost",
442
+ port: 5432,
443
+ database: "mydb",
444
+ user: "postgres",
445
+ password: "password",
446
+ });
447
+ ```
448
+
449
+ ### Advanced Configuration
450
+
451
+ ```ts
452
+ const vectorStore = new PgVector({
453
+ id: 'pg-vector',
454
+ connectionString: "postgresql://user:password@localhost:5432/mydb",
455
+ schemaName: "custom_schema",
456
+ max: 30,
457
+ idleTimeoutMillis: 60000,
458
+ pgPoolOptions: {
459
+ connectionTimeoutMillis: 5000,
460
+ allowExitOnIdle: true,
461
+ },
462
+ });
463
+ ```
464
+
465
+ ## Methods
466
+
467
+ ### createIndex()
468
+
469
+ #### IndexConfig
470
+
471
+ #### Memory Requirements
472
+
473
+ HNSW indexes require significant shared memory during construction. For 100K vectors:
474
+
475
+ - Small dimensions (64d): ~60MB with default settings
476
+ - Medium dimensions (256d): ~180MB with default settings
477
+ - Large dimensions (384d+): ~250MB+ with default settings
478
+
479
+ Higher M values or efConstruction values will increase memory requirements significantly. Adjust your system's shared memory limits if needed.
480
+
481
+ ### upsert()
482
+
483
+ ### query()
484
+
485
+ ### listIndexes()
486
+
487
+ Returns an array of index names as strings.
488
+
489
+ ### describeIndex()
490
+
491
+ Returns:
492
+
493
+ ```typescript
494
+ interface PGIndexStats {
495
+ dimension: number;
496
+ count: number;
497
+ metric: "cosine" | "euclidean" | "dotproduct";
498
+ type: "flat" | "hnsw" | "ivfflat";
499
+ config: {
500
+ m?: number;
501
+ efConstruction?: number;
502
+ lists?: number;
503
+ probes?: number;
504
+ };
505
+ }
506
+ ```
507
+
508
+ ### deleteIndex()
509
+
510
+ ### updateVector()
511
+
512
+ Update a single vector by ID or by metadata filter. Either `id` or `filter` must be provided, but not both.
513
+
514
+ Updates an existing vector by ID or filter. At least one of vector or metadata must be provided in the update object.
515
+
516
+ ```typescript
517
+ // Update by ID
518
+ await pgVector.updateVector({
519
+ indexName: "my_vectors",
520
+ id: "vector123",
521
+ update: {
522
+ vector: [0.1, 0.2, 0.3],
523
+ metadata: { label: "updated" },
524
+ },
525
+ });
526
+
527
+ // Update by filter
528
+ await pgVector.updateVector({
529
+ indexName: "my_vectors",
530
+ filter: { category: "product" },
531
+ update: {
532
+ metadata: { status: "reviewed" },
533
+ },
534
+ });
535
+ ```
536
+
537
+ ### deleteVector()
538
+
539
+ Deletes a single vector by ID from the specified index.
540
+
541
+ ```typescript
542
+ await pgVector.deleteVector({ indexName: "my_vectors", id: "vector123" });
543
+ ```
544
+
545
+ ### deleteVectors()
546
+
547
+ Delete multiple vectors by IDs or by metadata filter. Either `ids` or `filter` must be provided, but not both.
548
+
549
+ ### disconnect()
550
+
551
+ Closes the database connection pool. Should be called when done using the store.
552
+
553
+ ### buildIndex()
554
+
555
+ Builds or rebuilds an index with specified metric and configuration. Will drop any existing index before creating the new one.
556
+
557
+ ```typescript
558
+ // Define HNSW index
559
+ await pgVector.buildIndex("my_vectors", "cosine", {
560
+ type: "hnsw",
561
+ hnsw: {
562
+ m: 8,
563
+ efConstruction: 32,
564
+ },
565
+ });
566
+
567
+ // Define IVF index
568
+ await pgVector.buildIndex("my_vectors", "cosine", {
569
+ type: "ivfflat",
570
+ ivf: {
571
+ lists: 100,
572
+ },
573
+ });
574
+
575
+ // Define flat index
576
+ await pgVector.buildIndex("my_vectors", "cosine", {
577
+ type: "flat",
578
+ });
579
+ ```
580
+
581
+ ## Response Types
582
+
583
+ Query results are returned in this format:
584
+
585
+ ```typescript
586
+ interface QueryResult {
587
+ id: string;
588
+ score: number;
589
+ metadata: Record<string, any>;
590
+ vector?: number[]; // Only included if includeVector is true
591
+ }
592
+ ```
593
+
594
+ ## Error Handling
595
+
596
+ The store throws typed errors that can be caught:
597
+
598
+ ```typescript
599
+ try {
600
+ await store.query({
601
+ indexName: "index_name",
602
+ queryVector: queryVector,
603
+ });
604
+ } catch (error) {
605
+ if (error instanceof VectorStoreError) {
606
+ console.log(error.code); // 'connection_failed' | 'invalid_dimension' | etc
607
+ console.log(error.details); // Additional error context
608
+ }
609
+ }
610
+ ```
611
+
612
+ ## Index Configuration Guide
613
+
614
+ ### Performance Optimization
615
+
616
+ #### IVFFlat Tuning
617
+
618
+ - **lists parameter**: Set to `sqrt(n) * 2` where n is the number of vectors
619
+ - More lists = better accuracy but slower build time
620
+ - Fewer lists = faster build but potentially lower accuracy
621
+
622
+ #### HNSW Tuning
623
+
624
+ - **m parameter**:
625
+ - 8-16: Moderate accuracy, lower memory
626
+ - 16-32: High accuracy, moderate memory
627
+ - 32-64: Very high accuracy, high memory
628
+ - **efConstruction**:
629
+ - 32-64: Fast build, good quality
630
+ - 64-128: Slower build, better quality
631
+ - 128-256: Slowest build, best quality
632
+
633
+ ### Index Recreation Behavior
634
+
635
+ The system automatically detects configuration changes and only rebuilds indexes when necessary:
636
+
637
+ - Same configuration: Index is kept (no recreation)
638
+ - Changed configuration: Index is dropped and rebuilt
639
+ - This prevents the performance issues from unnecessary index recreations
640
+
641
+ ## Best Practices
642
+
643
+ - Regularly evaluate your index configuration to ensure optimal performance.
644
+ - Adjust parameters like `lists` and `m` based on dataset size and query requirements.
645
+ - **Monitor index performance** using `describeIndex()` to track usage
646
+ - Rebuild indexes periodically to maintain efficiency, especially after significant data changes
647
+
648
+ ## Direct Pool Access
649
+
650
+ The `PgVector` class exposes its underlying PostgreSQL connection pool as a public field:
651
+
652
+ ```typescript
653
+ pgVector.pool; // instance of pg.Pool
654
+ ```
655
+
656
+ This enables advanced usage such as running direct SQL queries, managing transactions, or monitoring pool state. When using the pool directly:
657
+
658
+ - You are responsible for releasing clients (`client.release()`) after use.
659
+ - The pool remains accessible after calling `disconnect()`, but new queries will fail.
660
+ - Direct access bypasses any validation or transaction logic provided by PgVector methods.
661
+
662
+ This design supports advanced use cases but requires careful resource management by the user.
663
+
664
+ ## Usage Example
665
+
666
+ ### Local embeddings with fastembed
667
+
668
+ Embeddings are numeric vectors used by memory's `semanticRecall` to retrieve related messages by meaning (not keywords). This setup uses `@mastra/fastembed` to generate vector embeddings.
669
+
670
+ Install `fastembed` to get started:
671
+
672
+ ```bash
673
+ npm install @mastra/fastembed@beta
674
+ ```
675
+
676
+ Add the following to your agent:
677
+
678
+ ```typescript title="src/mastra/agents/example-pg-agent.ts"
679
+ import { Memory } from "@mastra/memory";
680
+ import { Agent } from "@mastra/core/agent";
681
+ import { PostgresStore, PgVector } from "@mastra/pg";
682
+ import { fastembed } from "@mastra/fastembed";
683
+
684
+ export const pgAgent = new Agent({
685
+ id: "pg-agent",
686
+ name: "PG Agent",
687
+ instructions:
688
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
689
+ model: "openai/gpt-5.1",
690
+ memory: new Memory({
691
+ storage: new PostgresStore({
692
+ id: 'pg-agent-storage',
693
+ connectionString: process.env.DATABASE_URL!,
694
+ }),
695
+ vector: new PgVector({
696
+ id: 'pg-agent-vector',
697
+ connectionString: process.env.DATABASE_URL!,
698
+ }),
699
+ embedder: fastembed,
700
+ options: {
701
+ lastMessages: 10,
702
+ semanticRecall: {
703
+ topK: 3,
704
+ messageRange: 2,
705
+ },
706
+ },
707
+ }),
708
+ });
709
+ ```
710
+
711
+ ## Related
712
+
713
+ - [Metadata Filters](../rag/metadata-filters)
714
+
715
+ ---
716
+
717
+ ## Reference: Upstash Vector Store
718
+
719
+ > Documentation for the UpstashVector class in Mastra, which provides vector search using Upstash Vector.
720
+
721
+ The UpstashVector class provides vector search using [Upstash Vector](https://upstash.com/vector), a serverless vector database service that provides vector similarity search with metadata filtering capabilities and hybrid search support.
722
+
723
+ ## Constructor Options
724
+
725
+ ## Methods
726
+
727
+ ### createIndex()
728
+
729
+ Note: This method is a no-op for Upstash as indexes are created automatically.
730
+
731
+ ### upsert()
732
+
733
+ ### query()
734
+
735
+ ### listIndexes()
736
+
737
+ Returns an array of index names (namespaces) as strings.
738
+
739
+ ### describeIndex()
740
+
741
+ Returns:
742
+
743
+ ```typescript
744
+ interface IndexStats {
745
+ dimension: number;
746
+ count: number;
747
+ metric: "cosine" | "euclidean" | "dotproduct";
748
+ }
749
+ ```
750
+
751
+ ### deleteIndex()
752
+
753
+ ### updateVector()
754
+
755
+ The `update` object can have the following properties:
756
+
757
+ - `vector` (optional): An array of numbers representing the new dense vector.
758
+ - `sparseVector` (optional): A sparse vector object with `indices` and `values` arrays for hybrid indexes.
759
+ - `metadata` (optional): A record of key-value pairs for metadata.
760
+
761
+ ### deleteVector()
762
+
763
+ Attempts to delete an item by its ID from the specified index. Logs an error message if the deletion fails.
764
+
765
+ ## Hybrid Vector Search
766
+
767
+ Upstash Vector supports hybrid search that combines semantic search (dense vectors) with keyword-based search (sparse vectors) for improved relevance and accuracy.
768
+
769
+ ### Basic Hybrid Usage
770
+
771
+ ```typescript
772
+ import { UpstashVector } from "@mastra/upstash";
773
+
774
+ const vectorStore = new UpstashVector({
775
+ id: 'upstash-vector',
776
+ url: process.env.UPSTASH_VECTOR_URL,
777
+ token: process.env.UPSTASH_VECTOR_TOKEN,
778
+ });
779
+
780
+ // Upsert vectors with both dense and sparse components
781
+ const denseVectors = [
782
+ [0.1, 0.2, 0.3],
783
+ [0.4, 0.5, 0.6],
784
+ ];
785
+ const sparseVectors = [
786
+ { indices: [1, 5, 10], values: [0.8, 0.6, 0.4] },
787
+ { indices: [2, 6, 11], values: [0.7, 0.5, 0.3] },
788
+ ];
789
+
790
+ await vectorStore.upsert({
791
+ indexName: "hybrid-index",
792
+ vectors: denseVectors,
793
+ sparseVectors: sparseVectors,
794
+ metadata: [{ title: "Document 1" }, { title: "Document 2" }],
795
+ });
796
+
797
+ // Query with hybrid search
798
+ const results = await vectorStore.query({
799
+ indexName: "hybrid-index",
800
+ queryVector: [0.1, 0.2, 0.3],
801
+ sparseVector: { indices: [1, 5], values: [0.9, 0.7] },
802
+ topK: 10,
803
+ });
804
+ ```
805
+
806
+ ### Advanced Hybrid Search Options
807
+
808
+ ```typescript
809
+ import { FusionAlgorithm, QueryMode } from "@upstash/vector";
810
+
811
+ // Query with specific fusion algorithm
812
+ const fusionResults = await vectorStore.query({
813
+ indexName: "hybrid-index",
814
+ queryVector: [0.1, 0.2, 0.3],
815
+ sparseVector: { indices: [1, 5], values: [0.9, 0.7] },
816
+ fusionAlgorithm: FusionAlgorithm.RRF,
817
+ topK: 10,
818
+ });
819
+
820
+ // Dense-only search
821
+ const denseResults = await vectorStore.query({
822
+ indexName: "hybrid-index",
823
+ queryVector: [0.1, 0.2, 0.3],
824
+ queryMode: QueryMode.DENSE,
825
+ topK: 10,
826
+ });
827
+
828
+ // Sparse-only search
829
+ const sparseResults = await vectorStore.query({
830
+ indexName: "hybrid-index",
831
+ queryVector: [0.1, 0.2, 0.3], // Still required for index structure
832
+ sparseVector: { indices: [1, 5], values: [0.9, 0.7] },
833
+ queryMode: QueryMode.SPARSE,
834
+ topK: 10,
835
+ });
836
+ ```
837
+
838
+ ### Updating Hybrid Vectors
839
+
840
+ ```typescript
841
+ // Update both dense and sparse components
842
+ await vectorStore.updateVector({
843
+ indexName: "hybrid-index",
844
+ id: "vector-id",
845
+ update: {
846
+ vector: [0.2, 0.3, 0.4],
847
+ sparseVector: { indices: [2, 7, 12], values: [0.9, 0.8, 0.6] },
848
+ metadata: { title: "Updated Document" },
849
+ },
850
+ });
851
+ ```
852
+
853
+ ## Response Types
854
+
855
+ Query results are returned in this format:
856
+
857
+ ```typescript
858
+ interface QueryResult {
859
+ id: string;
860
+ score: number;
861
+ metadata: Record<string, any>;
862
+ vector?: number[]; // Only included if includeVector is true
863
+ }
864
+ ```
865
+
866
+ ## Error Handling
867
+
868
+ The store throws typed errors that can be caught:
869
+
870
+ ```typescript
871
+ try {
872
+ await store.query({
873
+ indexName: "index_name",
874
+ queryVector: queryVector,
875
+ });
876
+ } catch (error) {
877
+ if (error instanceof VectorStoreError) {
878
+ console.log(error.code); // 'connection_failed' | 'invalid_dimension' | etc
879
+ console.log(error.details); // Additional error context
880
+ }
881
+ }
882
+ ```
883
+
884
+ ## Environment Variables
885
+
886
+ Required environment variables:
887
+
888
+ - `UPSTASH_VECTOR_URL`: Your Upstash Vector database URL
889
+ - `UPSTASH_VECTOR_TOKEN`: Your Upstash Vector API token
890
+
891
+ ## Usage Example
892
+
893
+ ### Local embeddings with fastembed
894
+
895
+ Embeddings are numeric vectors used by memory's `semanticRecall` to retrieve related messages by meaning (not keywords). This setup uses `@mastra/fastembed` to generate vector embeddings.
896
+
897
+ Install `fastembed` to get started:
898
+
899
+ ```bash
900
+ npm install @mastra/fastembed@beta
901
+ ```
902
+
903
+ Add the following to your agent:
904
+
905
+ ```typescript title="src/mastra/agents/example-upstash-agent.ts"
906
+ import { Memory } from "@mastra/memory";
907
+ import { Agent } from "@mastra/core/agent";
908
+ import { UpstashStore, UpstashVector } from "@mastra/upstash";
909
+ import { fastembed } from "@mastra/fastembed";
910
+
911
+ export const upstashAgent = new Agent({
912
+ id: "upstash-agent",
913
+ name: "Upstash Agent",
914
+ instructions:
915
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
916
+ model: "openai/gpt-5.1",
917
+ memory: new Memory({
918
+ storage: new UpstashStore({
919
+ id: 'upstash-agent-storage',
920
+ url: process.env.UPSTASH_REDIS_REST_URL!,
921
+ token: process.env.UPSTASH_REDIS_REST_TOKEN!,
922
+ }),
923
+ vector: new UpstashVector({
924
+ id: 'upstash-agent-vector',
925
+ url: process.env.UPSTASH_VECTOR_REST_URL!,
926
+ token: process.env.UPSTASH_VECTOR_REST_TOKEN!,
927
+ }),
928
+ embedder: fastembed,
929
+ options: {
930
+ lastMessages: 10,
931
+ semanticRecall: {
932
+ topK: 3,
933
+ messageRange: 2,
934
+ },
935
+ },
936
+ }),
937
+ });
938
+ ```
939
+
940
+ ## Related
941
+
942
+ - [Metadata Filters](../rag/metadata-filters)