@mastra/s3vectors 1.0.0-beta.2 → 1.0.0-beta.3

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,638 @@
1
+ > Guide on vector storage options in Mastra, including embedded and dedicated vector databases for similarity search.
2
+
3
+ # Storing Embeddings in A Vector Database
4
+
5
+ After generating embeddings, you need to store them in a database that supports vector similarity search. Mastra provides a consistent interface for storing and querying embeddings across various vector databases.
6
+
7
+ ## Supported Databases
8
+
9
+ **mongodb:**
10
+
11
+ ```ts title="vector-store.ts"
12
+ import { MongoDBVector } from "@mastra/mongodb";
13
+
14
+ const store = new MongoDBVector({
15
+ uri: process.env.MONGODB_URI,
16
+ dbName: process.env.MONGODB_DATABASE,
17
+ });
18
+ await store.createIndex({
19
+ indexName: "myCollection",
20
+ dimension: 1536,
21
+ });
22
+ await store.upsert({
23
+ indexName: "myCollection",
24
+ vectors: embeddings,
25
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
26
+ });
27
+ ```
28
+
29
+ ### Using MongoDB Atlas Vector search
30
+
31
+ For detailed setup instructions and best practices, see the [official MongoDB Atlas Vector Search documentation](https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-overview/?utm_campaign=devrel&utm_source=third-party-content&utm_medium=cta&utm_content=mastra-docs).
32
+
33
+
34
+
35
+ **pg-vector:**
36
+
37
+ ```ts title="vector-store.ts"
38
+ import { PgVector } from "@mastra/pg";
39
+
40
+ const store = new PgVector({
41
+ id: 'pg-vector',
42
+ connectionString: process.env.POSTGRES_CONNECTION_STRING,
43
+ });
44
+
45
+ await store.createIndex({
46
+ indexName: "myCollection",
47
+ dimension: 1536,
48
+ });
49
+
50
+ await store.upsert({
51
+ indexName: "myCollection",
52
+ vectors: embeddings,
53
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
54
+ });
55
+ ```
56
+
57
+ ### Using PostgreSQL with pgvector
58
+
59
+ PostgreSQL with the pgvector extension is a good solution for teams already using PostgreSQL who want to minimize infrastructure complexity.
60
+ For detailed setup instructions and best practices, see the [official pgvector repository](https://github.com/pgvector/pgvector).
61
+
62
+
63
+
64
+ **pinecone:**
65
+
66
+ ```ts title="vector-store.ts"
67
+ import { PineconeVector } from "@mastra/pinecone";
68
+
69
+ const store = new PineconeVector({
70
+ id: 'pinecone-vector',
71
+ apiKey: process.env.PINECONE_API_KEY,
72
+ });
73
+ await store.createIndex({
74
+ indexName: "myCollection",
75
+ dimension: 1536,
76
+ });
77
+ await store.upsert({
78
+ indexName: "myCollection",
79
+ vectors: embeddings,
80
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
81
+ });
82
+ ```
83
+
84
+
85
+
86
+ **qdrant:**
87
+
88
+ ```ts title="vector-store.ts"
89
+ import { QdrantVector } from "@mastra/qdrant";
90
+
91
+ const store = new QdrantVector({
92
+ id: 'qdrant-vector',
93
+ url: process.env.QDRANT_URL,
94
+ apiKey: process.env.QDRANT_API_KEY,
95
+ });
96
+
97
+ await store.createIndex({
98
+ indexName: "myCollection",
99
+ dimension: 1536,
100
+ });
101
+
102
+ await store.upsert({
103
+ indexName: "myCollection",
104
+ vectors: embeddings,
105
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
106
+ });
107
+ ```
108
+
109
+
110
+
111
+ **chroma:**
112
+
113
+ ```ts title="vector-store.ts"
114
+ import { ChromaVector } from "@mastra/chroma";
115
+
116
+ // Running Chroma locally
117
+ // const store = new ChromaVector()
118
+
119
+ // Running on Chroma Cloud
120
+ const store = new ChromaVector({
121
+ id: 'chroma-vector',
122
+ apiKey: process.env.CHROMA_API_KEY,
123
+ tenant: process.env.CHROMA_TENANT,
124
+ database: process.env.CHROMA_DATABASE,
125
+ });
126
+
127
+ await store.createIndex({
128
+ indexName: "myCollection",
129
+ dimension: 1536,
130
+ });
131
+
132
+ await store.upsert({
133
+ indexName: "myCollection",
134
+ vectors: embeddings,
135
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
136
+ });
137
+ ```
138
+
139
+
140
+
141
+ **astra:**
142
+
143
+ ```ts title="vector-store.ts"
144
+ import { AstraVector } from "@mastra/astra";
145
+
146
+ const store = new AstraVector({
147
+ token: process.env.ASTRA_DB_TOKEN,
148
+ endpoint: process.env.ASTRA_DB_ENDPOINT,
149
+ keyspace: process.env.ASTRA_DB_KEYSPACE,
150
+ });
151
+
152
+ await store.createIndex({
153
+ indexName: "myCollection",
154
+ dimension: 1536,
155
+ });
156
+
157
+ await store.upsert({
158
+ indexName: "myCollection",
159
+ vectors: embeddings,
160
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
161
+ });
162
+ ```
163
+
164
+
165
+
166
+ **libsql:**
167
+
168
+ ```ts title="vector-store.ts"
169
+ import { LibSQLVector } from "@mastra/core/vector/libsql";
170
+
171
+ const store = new LibSQLVector({
172
+ id: 'libsql-vector',
173
+ connectionUrl: process.env.DATABASE_URL,
174
+ authToken: process.env.DATABASE_AUTH_TOKEN, // Optional: for Turso cloud databases
175
+ });
176
+
177
+ await store.createIndex({
178
+ indexName: "myCollection",
179
+ dimension: 1536,
180
+ });
181
+
182
+ await store.upsert({
183
+ indexName: "myCollection",
184
+ vectors: embeddings,
185
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
186
+ });
187
+ ```
188
+
189
+
190
+
191
+ **upstash:**
192
+
193
+ ```ts title="vector-store.ts"
194
+ import { UpstashVector } from "@mastra/upstash";
195
+
196
+ // In upstash they refer to the store as an index
197
+ const store = new UpstashVector({
198
+ id: 'upstash-vector',
199
+ url: process.env.UPSTASH_URL,
200
+ token: process.env.UPSTASH_TOKEN,
201
+ });
202
+
203
+ // There is no store.createIndex call here, Upstash creates indexes (known as namespaces in Upstash) automatically
204
+ // when you upsert if that namespace does not exist yet.
205
+ await store.upsert({
206
+ indexName: "myCollection", // the namespace name in Upstash
207
+ vectors: embeddings,
208
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
209
+ });
210
+ ```
211
+
212
+
213
+
214
+ **cloudflare:**
215
+
216
+ ```ts title="vector-store.ts"
217
+ import { CloudflareVector } from "@mastra/vectorize";
218
+
219
+ const store = new CloudflareVector({
220
+ accountId: process.env.CF_ACCOUNT_ID,
221
+ apiToken: process.env.CF_API_TOKEN,
222
+ });
223
+ await store.createIndex({
224
+ indexName: "myCollection",
225
+ dimension: 1536,
226
+ });
227
+ await store.upsert({
228
+ indexName: "myCollection",
229
+ vectors: embeddings,
230
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
231
+ });
232
+ ```
233
+
234
+
235
+
236
+ **opensearch:**
237
+
238
+ ```ts title="vector-store.ts"
239
+ import { OpenSearchVector } from "@mastra/opensearch";
240
+
241
+ const store = new OpenSearchVector({ url: process.env.OPENSEARCH_URL });
242
+
243
+ await store.createIndex({
244
+ indexName: "my-collection",
245
+ dimension: 1536,
246
+ });
247
+
248
+ await store.upsert({
249
+ indexName: "my-collection",
250
+ vectors: embeddings,
251
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
252
+ });
253
+ ```
254
+
255
+
256
+
257
+ **elasticsearch:**
258
+
259
+ ```ts title="vector-store.ts"
260
+ import { ElasticSearchVector } from "@mastra/elasticsearch";
261
+
262
+ const store = new ElasticSearchVector({ url: process.env.ELASTICSEARCH_URL });
263
+
264
+ await store.createIndex({
265
+ indexName: "my-collection",
266
+ dimension: 1536,
267
+ });
268
+
269
+ await store.upsert({
270
+ indexName: "my-collection",
271
+ vectors: embeddings,
272
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
273
+ });
274
+ ```
275
+
276
+
277
+ **couchbase:**
278
+
279
+ ```ts title="vector-store.ts"
280
+ import { CouchbaseVector } from "@mastra/couchbase";
281
+
282
+ const store = new CouchbaseVector({
283
+ connectionString: process.env.COUCHBASE_CONNECTION_STRING,
284
+ username: process.env.COUCHBASE_USERNAME,
285
+ password: process.env.COUCHBASE_PASSWORD,
286
+ bucketName: process.env.COUCHBASE_BUCKET,
287
+ scopeName: process.env.COUCHBASE_SCOPE,
288
+ collectionName: process.env.COUCHBASE_COLLECTION,
289
+ });
290
+ await store.createIndex({
291
+ indexName: "myCollection",
292
+ dimension: 1536,
293
+ });
294
+ await store.upsert({
295
+ indexName: "myCollection",
296
+ vectors: embeddings,
297
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
298
+ });
299
+ ```
300
+
301
+
302
+ **lancedb:**
303
+
304
+ ```ts title="vector-store.ts"
305
+ import { LanceVectorStore } from "@mastra/lance";
306
+
307
+ const store = await LanceVectorStore.create("/path/to/db");
308
+
309
+ await store.createIndex({
310
+ tableName: "myVectors",
311
+ indexName: "myCollection",
312
+ dimension: 1536,
313
+ });
314
+
315
+ await store.upsert({
316
+ tableName: "myVectors",
317
+ vectors: embeddings,
318
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
319
+ });
320
+ ```
321
+
322
+ ### Using LanceDB
323
+
324
+ LanceDB is an embedded vector database built on the Lance columnar format, suitable for local development or cloud deployment.
325
+ For detailed setup instructions and best practices, see the [official LanceDB documentation](https://lancedb.github.io/lancedb/).
326
+
327
+
328
+ **s3vectors:**
329
+
330
+ ```ts title="vector-store.ts"
331
+ import { S3Vectors } from "@mastra/s3vectors";
332
+
333
+ const store = new S3Vectors({
334
+ vectorBucketName: "my-vector-bucket",
335
+ clientConfig: {
336
+ region: "us-east-1",
337
+ },
338
+ nonFilterableMetadataKeys: ["content"],
339
+ });
340
+
341
+ await store.createIndex({
342
+ indexName: "my-index",
343
+ dimension: 1536,
344
+ });
345
+ await store.upsert({
346
+ indexName: "my-index",
347
+ vectors: embeddings,
348
+ metadata: chunks.map((chunk) => ({ text: chunk.text })),
349
+ });
350
+ ```
351
+
352
+
353
+
354
+ ## Using Vector Storage
355
+
356
+ Once initialized, all vector stores share the same interface for creating indexes, upserting embeddings, and querying.
357
+
358
+ ### Creating Indexes
359
+
360
+ Before storing embeddings, you need to create an index with the appropriate dimension size for your embedding model:
361
+
362
+ ```ts title="store-embeddings.ts"
363
+ // Create an index with dimension 1536 (for text-embedding-3-small)
364
+ await store.createIndex({
365
+ indexName: "myCollection",
366
+ dimension: 1536,
367
+ });
368
+ ```
369
+
370
+ The dimension size must match the output dimension of your chosen embedding model. Common dimension sizes are:
371
+
372
+ - OpenAI text-embedding-3-small: 1536 dimensions (or custom, e.g., 256)
373
+ - Cohere embed-multilingual-v3: 1024 dimensions
374
+ - Google text-embedding-004: 768 dimensions (or custom)
375
+
376
+ important
377
+ Index dimensions cannot be changed after creation. To use a different model, delete and recreate the index with the new dimension size.
378
+
379
+ ### Naming Rules for Databases
380
+
381
+ Each vector database enforces specific naming conventions for indexes and collections to ensure compatibility and prevent conflicts.
382
+
383
+ **mongodb:**
384
+
385
+ Collection (index) names must:
386
+ - Start with a letter or underscore
387
+ - Be up to 120 bytes long
388
+ - Contain only letters, numbers, underscores, or dots
389
+ - Cannot contain `$` or the null character
390
+ - Example: `my_collection.123` is valid
391
+ - Example: `my-index` is not valid (contains hyphen)
392
+ - Example: `My$Collection` is not valid (contains `$`)
393
+
394
+ **pgVector:**
395
+
396
+ Index names must:
397
+ - Start with a letter or underscore
398
+ - Contain only letters, numbers, and underscores
399
+ - Example: `my_index_123` is valid
400
+ - Example: `my-index` is not valid (contains hyphen)
401
+
402
+ **pinecone:**
403
+
404
+ Index names must:
405
+ - Use only lowercase letters, numbers, and dashes
406
+ - Not contain dots (used for DNS routing)
407
+ - Not use non-Latin characters or emojis
408
+ - Have a combined length (with project ID) under 52 characters
409
+ - Example: `my-index-123` is valid
410
+ - Example: `my.index` is not valid (contains dot)
411
+
412
+ **qdrant:**
413
+
414
+ Collection names must:
415
+ - Be 1-255 characters long
416
+ - Not contain any of these special characters:
417
+ - `< > : " / \ | ? *`
418
+ - Null character (`\0`)
419
+ - Unit separator (`\u{1F}`)
420
+ - Example: `my_collection_123` is valid
421
+ - Example: `my/collection` is not valid (contains slash)
422
+
423
+ **chroma:**
424
+
425
+ Collection names must:
426
+ - Be 3-63 characters long
427
+ - Start and end with a letter or number
428
+ - Contain only letters, numbers, underscores, or hyphens
429
+ - Not contain consecutive periods (..)
430
+ - Not be a valid IPv4 address
431
+ - Example: `my-collection-123` is valid
432
+ - Example: `my..collection` is not valid (consecutive periods)
433
+
434
+ **astra:**
435
+
436
+ Collection names must:
437
+ - Not be empty
438
+ - Be 48 characters or less
439
+ - Contain only letters, numbers, and underscores
440
+ - Example: `my_collection_123` is valid
441
+ - Example: `my-collection` is not valid (contains hyphen)
442
+
443
+ **libsql:**
444
+
445
+ Index names must:
446
+ - Start with a letter or underscore
447
+ - Contain only letters, numbers, and underscores
448
+ - Example: `my_index_123` is valid
449
+ - Example: `my-index` is not valid (contains hyphen)
450
+
451
+ **upstash:**
452
+
453
+ Namespace names must:
454
+ - Be 2-100 characters long
455
+ - Contain only:
456
+ - Alphanumeric characters (a-z, A-Z, 0-9)
457
+ - Underscores, hyphens, dots
458
+ - Not start or end with special characters (_, -, .)
459
+ - Can be case-sensitive
460
+ - Example: `MyNamespace123` is valid
461
+ - Example: `_namespace` is not valid (starts with underscore)
462
+
463
+ **cloudflare:**
464
+
465
+ Index names must:
466
+ - Start with a letter
467
+ - Be shorter than 32 characters
468
+ - Contain only lowercase ASCII letters, numbers, and dashes
469
+ - Use dashes instead of spaces
470
+ - Example: `my-index-123` is valid
471
+ - Example: `My_Index` is not valid (uppercase and underscore)
472
+
473
+ **opensearch:**
474
+
475
+ Index names must:
476
+ - Use only lowercase letters
477
+ - Not begin with underscores or hyphens
478
+ - Not contain spaces, commas
479
+ - Not contain special characters (e.g. `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, `<`)
480
+ - Example: `my-index-123` is valid
481
+ - Example: `My_Index` is not valid (contains uppercase letters)
482
+ - Example: `_myindex` is not valid (begins with underscore)
483
+
484
+ **elasticsearch:**
485
+
486
+ Index names must:
487
+ - Use only lowercase letters
488
+ - Not exceed 255 bytes (counting multi-byte characters)
489
+ - Not begin with underscores, hyphens, or plus signs
490
+ - Not contain spaces, commas
491
+ - Not contain special characters (e.g. `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, `<`)
492
+ - Not be "." or ".."
493
+ - Not start with "." (deprecated except for system/hidden indices)
494
+ - Example: `my-index-123` is valid
495
+ - Example: `My_Index` is not valid (contains uppercase letters)
496
+ - Example: `_myindex` is not valid (begins with underscore)
497
+ - Example: `.myindex` is not valid (begins with dot, deprecated)
498
+
499
+ **s3vectors:**
500
+
501
+ Index names must:
502
+ - Be unique within the same vector bucket
503
+ - Be 3–63 characters long
504
+ - Use only lowercase letters (`a–z`), numbers (`0–9`), hyphens (`-`), and dots (`.`)
505
+ - Begin and end with a letter or number
506
+ - Example: `my-index.123` is valid
507
+ - Example: `my_index` is not valid (contains underscore)
508
+ - Example: `-myindex` is not valid (begins with hyphen)
509
+ - Example: `myindex-` is not valid (ends with hyphen)
510
+ - Example: `MyIndex` is not valid (contains uppercase letters)
511
+
512
+
513
+ ### Upserting Embeddings
514
+
515
+ After creating an index, you can store embeddings along with their basic metadata:
516
+
517
+ ```ts title="store-embeddings.ts"
518
+ // Store embeddings with their corresponding metadata
519
+ await store.upsert({
520
+ indexName: "myCollection", // index name
521
+ vectors: embeddings, // array of embedding vectors
522
+ metadata: chunks.map((chunk) => ({
523
+ text: chunk.text, // The original text content
524
+ id: chunk.id, // Optional unique identifier
525
+ })),
526
+ });
527
+ ```
528
+
529
+ The upsert operation:
530
+
531
+ - Takes an array of embedding vectors and their corresponding metadata
532
+ - Updates existing vectors if they share the same ID
533
+ - Creates new vectors if they don't exist
534
+ - Automatically handles batching for large datasets
535
+
536
+ ## Adding Metadata
537
+
538
+ Vector stores support rich metadata (any JSON-serializable fields) for filtering and organization. Since metadata is stored with no fixed schema, use consistent field naming to avoid unexpected query results.
539
+
540
+ important
541
+ Metadata is crucial for vector storage - without it, you'd only have numerical embeddings with no way to return the original text or filter results. Always store at least the source text as metadata.
542
+
543
+ ```ts
544
+ // Store embeddings with rich metadata for better organization and filtering
545
+ await store.upsert({
546
+ indexName: "myCollection",
547
+ vectors: embeddings,
548
+ metadata: chunks.map((chunk) => ({
549
+ // Basic content
550
+ text: chunk.text,
551
+ id: chunk.id,
552
+
553
+ // Document organization
554
+ source: chunk.source,
555
+ category: chunk.category,
556
+
557
+ // Temporal metadata
558
+ createdAt: new Date().toISOString(),
559
+ version: "1.0",
560
+
561
+ // Custom fields
562
+ language: chunk.language,
563
+ author: chunk.author,
564
+ confidenceScore: chunk.score,
565
+ })),
566
+ });
567
+ ```
568
+
569
+ Key metadata considerations:
570
+
571
+ - Be strict with field naming - inconsistencies like 'category' vs 'Category' will affect queries
572
+ - Only include fields you plan to filter or sort by - extra fields add overhead
573
+ - Add timestamps (e.g., 'createdAt', 'lastUpdated') to track content freshness
574
+
575
+ ## Deleting Vectors
576
+
577
+ When building RAG applications, you often need to clean up stale vectors when documents are deleted or updated. Mastra provides the `deleteVectors` method that supports deleting vectors by metadata filters, making it easy to remove all embeddings associated with a specific document.
578
+
579
+ ### Delete by Metadata Filter
580
+
581
+ The most common use case is deleting all vectors for a specific document when a user deletes it:
582
+
583
+ ```ts title="delete-vectors.ts"
584
+ // Delete all vectors for a specific document
585
+ await store.deleteVectors({
586
+ indexName: "myCollection",
587
+ filter: { docId: "document-123" },
588
+ });
589
+ ```
590
+
591
+ This is particularly useful when:
592
+ - A user deletes a document and you need to remove all its chunks
593
+ - You're re-indexing a document and want to remove old vectors first
594
+ - You need to clean up vectors for a specific user or tenant
595
+
596
+ ### Delete Multiple Documents
597
+
598
+ You can also use complex filters to delete vectors matching multiple conditions:
599
+
600
+ ```ts title="delete-vectors-advanced.ts"
601
+ // Delete all vectors for multiple documents
602
+ await store.deleteVectors({
603
+ indexName: "myCollection",
604
+ filter: {
605
+ docId: { $in: ["doc-1", "doc-2", "doc-3"] },
606
+ },
607
+ });
608
+
609
+ // Delete vectors for a specific user's documents
610
+ await store.deleteVectors({
611
+ indexName: "myCollection",
612
+ filter: {
613
+ $and: [
614
+ { userId: "user-123" },
615
+ { status: "archived" },
616
+ ],
617
+ },
618
+ });
619
+ ```
620
+
621
+ ### Delete by Vector IDs
622
+
623
+ If you have specific vector IDs to delete, you can pass them directly:
624
+
625
+ ```ts title="delete-by-ids.ts"
626
+ // Delete specific vectors by their IDs
627
+ await store.deleteVectors({
628
+ indexName: "myCollection",
629
+ ids: ["vec-1", "vec-2", "vec-3"],
630
+ });
631
+ ```
632
+
633
+ ## Best Practices
634
+
635
+ - Create indexes before bulk insertions
636
+ - Use batch operations for large insertions (the upsert method handles batching automatically)
637
+ - Only store metadata you'll query against
638
+ - Match embedding dimensions to your model (e.g., 1536 for `text-embedding-3-small`)