@mastra/couchbase 0.0.0-vector-query-sources-20250516172905 → 0.0.0-vector-query-tool-provider-options-20250828222356

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.
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
1
2
  import { MastraVector } from '@mastra/core/vector';
2
3
  import { connect, SearchRequest, VectorSearch, VectorQuery, MutateInSpec } from 'couchbase';
3
4
 
@@ -17,49 +18,47 @@ var CouchbaseVector = class extends MastraVector {
17
18
  bucket;
18
19
  scope;
19
20
  vector_dimension;
20
- constructor(paramsOrConnectionString, username, password, bucketName, scopeName, collectionName) {
21
- let connectionString_, username_, password_, bucketName_, scopeName_, collectionName_;
22
- if (typeof paramsOrConnectionString === "object" && paramsOrConnectionString !== null && "connectionString" in paramsOrConnectionString) {
23
- connectionString_ = paramsOrConnectionString.connectionString;
24
- username_ = paramsOrConnectionString.username;
25
- password_ = paramsOrConnectionString.password;
26
- bucketName_ = paramsOrConnectionString.bucketName;
27
- scopeName_ = paramsOrConnectionString.scopeName;
28
- collectionName_ = paramsOrConnectionString.collectionName;
29
- } else {
30
- if (arguments.length > 1) {
31
- console.warn(
32
- "Deprecation Warning: CouchbaseVector constructor positional arguments are deprecated. Please use a single object parameter instead. This signature will be removed on May 20th, 2025."
33
- );
34
- }
35
- connectionString_ = paramsOrConnectionString;
36
- username_ = username;
37
- password_ = password;
38
- bucketName_ = bucketName;
39
- scopeName_ = scopeName;
40
- collectionName_ = collectionName;
41
- }
21
+ constructor({ connectionString, username, password, bucketName, scopeName, collectionName }) {
42
22
  super();
43
- const baseClusterPromise = connect(connectionString_, {
44
- username: username_,
45
- password: password_,
46
- configProfile: "wanDevelopment"
47
- });
48
- const telemetry = this.__getTelemetry();
49
- this.clusterPromise = telemetry?.traceClass(baseClusterPromise, {
50
- spanNamePrefix: "couchbase-vector",
51
- attributes: {
52
- "vector.type": "couchbase"
53
- }
54
- }) ?? baseClusterPromise;
55
- this.cluster = null;
56
- this.bucketName = bucketName_;
57
- this.collectionName = collectionName_;
58
- this.scopeName = scopeName_;
59
- this.collection = null;
60
- this.bucket = null;
61
- this.scope = null;
62
- this.vector_dimension = null;
23
+ try {
24
+ const baseClusterPromise = connect(connectionString, {
25
+ username,
26
+ password,
27
+ configProfile: "wanDevelopment"
28
+ });
29
+ const telemetry = this.__getTelemetry();
30
+ this.clusterPromise = telemetry?.traceClass(baseClusterPromise, {
31
+ spanNamePrefix: "couchbase-vector",
32
+ attributes: {
33
+ "vector.type": "couchbase"
34
+ }
35
+ }) ?? baseClusterPromise;
36
+ this.cluster = null;
37
+ this.bucketName = bucketName;
38
+ this.collectionName = collectionName;
39
+ this.scopeName = scopeName;
40
+ this.collection = null;
41
+ this.bucket = null;
42
+ this.scope = null;
43
+ this.vector_dimension = null;
44
+ } catch (error) {
45
+ throw new MastraError(
46
+ {
47
+ id: "COUCHBASE_VECTOR_INITIALIZE_FAILED",
48
+ domain: ErrorDomain.STORAGE,
49
+ category: ErrorCategory.THIRD_PARTY,
50
+ details: {
51
+ connectionString,
52
+ username,
53
+ password,
54
+ bucketName,
55
+ scopeName,
56
+ collectionName
57
+ }
58
+ },
59
+ error
60
+ );
61
+ }
63
62
  }
64
63
  async getCollection() {
65
64
  if (!this.cluster) {
@@ -72,13 +71,12 @@ var CouchbaseVector = class extends MastraVector {
72
71
  }
73
72
  return this.collection;
74
73
  }
75
- async createIndex(params) {
76
- const { indexName, dimension, metric = "dotproduct" } = params;
77
- await this.getCollection();
78
- if (!Number.isInteger(dimension) || dimension <= 0) {
79
- throw new Error("Dimension must be a positive integer");
80
- }
74
+ async createIndex({ indexName, dimension, metric = "dotproduct" }) {
81
75
  try {
76
+ await this.getCollection();
77
+ if (!Number.isInteger(dimension) || dimension <= 0) {
78
+ throw new Error("Dimension must be a positive integer");
79
+ }
82
80
  await this.scope.searchIndexes().upsertIndex({
83
81
  name: indexName,
84
82
  sourceName: this.bucketName,
@@ -165,116 +163,191 @@ var CouchbaseVector = class extends MastraVector {
165
163
  await this.validateExistingIndex(indexName, dimension, metric);
166
164
  return;
167
165
  }
168
- throw error;
166
+ throw new MastraError(
167
+ {
168
+ id: "COUCHBASE_VECTOR_CREATE_INDEX_FAILED",
169
+ domain: ErrorDomain.STORAGE,
170
+ category: ErrorCategory.THIRD_PARTY,
171
+ details: {
172
+ indexName,
173
+ dimension,
174
+ metric
175
+ }
176
+ },
177
+ error
178
+ );
169
179
  }
170
180
  }
171
- async upsert(params) {
172
- const { vectors, metadata, ids } = params;
173
- await this.getCollection();
174
- if (!vectors || vectors.length === 0) {
175
- throw new Error("No vectors provided");
176
- }
177
- if (this.vector_dimension) {
178
- for (const vector of vectors) {
179
- if (!vector || this.vector_dimension !== vector.length) {
180
- throw new Error("Vector dimension mismatch");
181
+ async upsert({ vectors, metadata, ids }) {
182
+ try {
183
+ await this.getCollection();
184
+ if (!vectors || vectors.length === 0) {
185
+ throw new Error("No vectors provided");
186
+ }
187
+ if (this.vector_dimension) {
188
+ for (const vector of vectors) {
189
+ if (!vector || this.vector_dimension !== vector.length) {
190
+ throw new Error("Vector dimension mismatch");
191
+ }
181
192
  }
182
193
  }
183
- }
184
- const pointIds = ids || vectors.map(() => crypto.randomUUID());
185
- const records = vectors.map((vector, i) => {
186
- const metadataObj = metadata?.[i] || {};
187
- const record = {
188
- embedding: vector,
189
- metadata: metadataObj
190
- };
191
- if (metadataObj.text) {
192
- record.content = metadataObj.text;
194
+ const pointIds = ids || vectors.map(() => crypto.randomUUID());
195
+ const records = vectors.map((vector, i) => {
196
+ const metadataObj = metadata?.[i] || {};
197
+ const record = {
198
+ embedding: vector,
199
+ metadata: metadataObj
200
+ };
201
+ if (metadataObj.text) {
202
+ record.content = metadataObj.text;
203
+ }
204
+ return record;
205
+ });
206
+ const allPromises = [];
207
+ for (let i = 0; i < records.length; i++) {
208
+ allPromises.push(this.collection.upsert(pointIds[i], records[i]));
193
209
  }
194
- return record;
195
- });
196
- const allPromises = [];
197
- for (let i = 0; i < records.length; i++) {
198
- allPromises.push(this.collection.upsert(pointIds[i], records[i]));
210
+ await Promise.all(allPromises);
211
+ return pointIds;
212
+ } catch (error) {
213
+ throw new MastraError(
214
+ {
215
+ id: "COUCHBASE_VECTOR_UPSERT_FAILED",
216
+ domain: ErrorDomain.STORAGE,
217
+ category: ErrorCategory.THIRD_PARTY
218
+ },
219
+ error
220
+ );
199
221
  }
200
- await Promise.all(allPromises);
201
- return pointIds;
202
222
  }
203
- async query(params) {
204
- const { indexName, queryVector, topK = 10, includeVector = false } = params;
205
- await this.getCollection();
206
- const index_stats = await this.describeIndex(indexName);
207
- if (queryVector.length !== index_stats.dimension) {
208
- throw new Error(`Query vector dimension mismatch. Expected ${index_stats.dimension}, got ${queryVector.length}`);
209
- }
210
- let request = SearchRequest.create(
211
- VectorSearch.fromVectorQuery(VectorQuery.create("embedding", queryVector).numCandidates(topK))
212
- );
213
- const results = await this.scope.search(indexName, request, {
214
- fields: ["*"]
215
- });
216
- if (includeVector) {
217
- throw new Error("Including vectors in search results is not yet supported by the Couchbase vector store");
218
- }
219
- const output = [];
220
- for (const match of results.rows) {
221
- const cleanedMetadata = {};
222
- const fields = match.fields || {};
223
- for (const key in fields) {
224
- if (Object.prototype.hasOwnProperty.call(fields, key)) {
225
- const newKey = key.startsWith("metadata.") ? key.substring("metadata.".length) : key;
226
- cleanedMetadata[newKey] = fields[key];
227
- }
223
+ async query({ indexName, queryVector, topK = 10, includeVector = false }) {
224
+ try {
225
+ await this.getCollection();
226
+ const index_stats = await this.describeIndex({ indexName });
227
+ if (queryVector.length !== index_stats.dimension) {
228
+ throw new Error(
229
+ `Query vector dimension mismatch. Expected ${index_stats.dimension}, got ${queryVector.length}`
230
+ );
228
231
  }
229
- output.push({
230
- id: match.id,
231
- score: match.score || 0,
232
- metadata: cleanedMetadata
233
- // Use the cleaned metadata object
232
+ let request = SearchRequest.create(
233
+ VectorSearch.fromVectorQuery(VectorQuery.create("embedding", queryVector).numCandidates(topK))
234
+ );
235
+ const results = await this.scope.search(indexName, request, {
236
+ fields: ["*"]
234
237
  });
238
+ if (includeVector) {
239
+ throw new Error("Including vectors in search results is not yet supported by the Couchbase vector store");
240
+ }
241
+ const output = [];
242
+ for (const match of results.rows) {
243
+ const cleanedMetadata = {};
244
+ const fields = match.fields || {};
245
+ for (const key in fields) {
246
+ if (Object.prototype.hasOwnProperty.call(fields, key)) {
247
+ const newKey = key.startsWith("metadata.") ? key.substring("metadata.".length) : key;
248
+ cleanedMetadata[newKey] = fields[key];
249
+ }
250
+ }
251
+ output.push({
252
+ id: match.id,
253
+ score: match.score || 0,
254
+ metadata: cleanedMetadata
255
+ // Use the cleaned metadata object
256
+ });
257
+ }
258
+ return output;
259
+ } catch (error) {
260
+ throw new MastraError(
261
+ {
262
+ id: "COUCHBASE_VECTOR_QUERY_FAILED",
263
+ domain: ErrorDomain.STORAGE,
264
+ category: ErrorCategory.THIRD_PARTY,
265
+ details: {
266
+ indexName,
267
+ topK
268
+ }
269
+ },
270
+ error
271
+ );
235
272
  }
236
- return output;
237
273
  }
238
274
  async listIndexes() {
239
- await this.getCollection();
240
- const indexes = await this.scope.searchIndexes().getAllIndexes();
241
- return indexes?.map((index) => index.name) || [];
275
+ try {
276
+ await this.getCollection();
277
+ const indexes = await this.scope.searchIndexes().getAllIndexes();
278
+ return indexes?.map((index) => index.name) || [];
279
+ } catch (error) {
280
+ throw new MastraError(
281
+ {
282
+ id: "COUCHBASE_VECTOR_LIST_INDEXES_FAILED",
283
+ domain: ErrorDomain.STORAGE,
284
+ category: ErrorCategory.THIRD_PARTY
285
+ },
286
+ error
287
+ );
288
+ }
242
289
  }
243
290
  /**
244
291
  * Retrieves statistics about a vector index.
245
292
  *
246
- * @param params - The parameters for describing an index
247
- * @param params.indexName - The name of the index to describe
293
+ * @param {string} indexName - The name of the index to describe
248
294
  * @returns A promise that resolves to the index statistics including dimension, count and metric
249
295
  */
250
- async describeIndex(...args) {
251
- const params = this.normalizeArgs("describeIndex", args);
252
- const { indexName } = params;
253
- await this.getCollection();
254
- if (!(await this.listIndexes()).includes(indexName)) {
255
- throw new Error(`Index ${indexName} does not exist`);
296
+ async describeIndex({ indexName }) {
297
+ try {
298
+ await this.getCollection();
299
+ if (!(await this.listIndexes()).includes(indexName)) {
300
+ throw new Error(`Index ${indexName} does not exist`);
301
+ }
302
+ const index = await this.scope.searchIndexes().getIndex(indexName);
303
+ const dimensions = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.dims;
304
+ const count = -1;
305
+ const metric = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.similarity;
306
+ return {
307
+ dimension: dimensions,
308
+ count,
309
+ metric: Object.keys(DISTANCE_MAPPING).find(
310
+ (key) => DISTANCE_MAPPING[key] === metric
311
+ )
312
+ };
313
+ } catch (error) {
314
+ throw new MastraError(
315
+ {
316
+ id: "COUCHBASE_VECTOR_DESCRIBE_INDEX_FAILED",
317
+ domain: ErrorDomain.STORAGE,
318
+ category: ErrorCategory.THIRD_PARTY,
319
+ details: {
320
+ indexName
321
+ }
322
+ },
323
+ error
324
+ );
256
325
  }
257
- const index = await this.scope.searchIndexes().getIndex(indexName);
258
- const dimensions = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.dims;
259
- const count = -1;
260
- const metric = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.similarity;
261
- return {
262
- dimension: dimensions,
263
- count,
264
- metric: Object.keys(DISTANCE_MAPPING).find(
265
- (key) => DISTANCE_MAPPING[key] === metric
266
- )
267
- };
268
326
  }
269
- async deleteIndex(...args) {
270
- const params = this.normalizeArgs("deleteIndex", args);
271
- const { indexName } = params;
272
- await this.getCollection();
273
- if (!(await this.listIndexes()).includes(indexName)) {
274
- throw new Error(`Index ${indexName} does not exist`);
327
+ async deleteIndex({ indexName }) {
328
+ try {
329
+ await this.getCollection();
330
+ if (!(await this.listIndexes()).includes(indexName)) {
331
+ throw new Error(`Index ${indexName} does not exist`);
332
+ }
333
+ await this.scope.searchIndexes().dropIndex(indexName);
334
+ this.vector_dimension = null;
335
+ } catch (error) {
336
+ if (error instanceof MastraError) {
337
+ throw error;
338
+ }
339
+ throw new MastraError(
340
+ {
341
+ id: "COUCHBASE_VECTOR_DELETE_INDEX_FAILED",
342
+ domain: ErrorDomain.STORAGE,
343
+ category: ErrorCategory.THIRD_PARTY,
344
+ details: {
345
+ indexName
346
+ }
347
+ },
348
+ error
349
+ );
275
350
  }
276
- await this.scope.searchIndexes().dropIndex(indexName);
277
- this.vector_dimension = null;
278
351
  }
279
352
  /**
280
353
  * Updates a vector by its ID with the provided vector and/or metadata.
@@ -286,28 +359,42 @@ var CouchbaseVector = class extends MastraVector {
286
359
  * @returns A promise that resolves when the update is complete.
287
360
  * @throws Will throw an error if no updates are provided or if the update operation fails.
288
361
  */
289
- async updateVector(...args) {
290
- const params = this.normalizeArgs("updateVector", args);
291
- const { id, update } = params;
292
- if (!update.vector && !update.metadata) {
293
- throw new Error("No updates provided");
294
- }
295
- if (update.vector && this.vector_dimension && update.vector.length !== this.vector_dimension) {
296
- throw new Error("Vector dimension mismatch");
297
- }
298
- const collection = await this.getCollection();
362
+ async updateVector({ id, update }) {
299
363
  try {
300
- await collection.get(id);
301
- } catch (err) {
302
- if (err.code === 13 || err.message?.includes("document not found")) {
303
- throw new Error(`Vector with id ${id} does not exist`);
364
+ if (!update.vector && !update.metadata) {
365
+ throw new Error("No updates provided");
366
+ }
367
+ if (update.vector && this.vector_dimension && update.vector.length !== this.vector_dimension) {
368
+ throw new Error("Vector dimension mismatch");
304
369
  }
305
- throw err;
370
+ const collection = await this.getCollection();
371
+ try {
372
+ await collection.get(id);
373
+ } catch (err) {
374
+ if (err.code === 13 || err.message?.includes("document not found")) {
375
+ throw new Error(`Vector with id ${id} does not exist`);
376
+ }
377
+ throw err;
378
+ }
379
+ const specs = [];
380
+ if (update.vector) specs.push(MutateInSpec.replace("embedding", update.vector));
381
+ if (update.metadata) specs.push(MutateInSpec.replace("metadata", update.metadata));
382
+ await collection.mutateIn(id, specs);
383
+ } catch (error) {
384
+ throw new MastraError(
385
+ {
386
+ id: "COUCHBASE_VECTOR_UPDATE_FAILED",
387
+ domain: ErrorDomain.STORAGE,
388
+ category: ErrorCategory.THIRD_PARTY,
389
+ details: {
390
+ id,
391
+ hasVectorUpdate: !!update.vector,
392
+ hasMetadataUpdate: !!update.metadata
393
+ }
394
+ },
395
+ error
396
+ );
306
397
  }
307
- const specs = [];
308
- if (update.vector) specs.push(MutateInSpec.replace("embedding", update.vector));
309
- if (update.metadata) specs.push(MutateInSpec.replace("metadata", update.metadata));
310
- await collection.mutateIn(id, specs);
311
398
  }
312
399
  /**
313
400
  * Deletes a vector by its ID.
@@ -316,20 +403,51 @@ var CouchbaseVector = class extends MastraVector {
316
403
  * @returns A promise that resolves when the deletion is complete.
317
404
  * @throws Will throw an error if the deletion operation fails.
318
405
  */
319
- async deleteVector(...args) {
320
- const params = this.normalizeArgs("deleteVector", args);
321
- const { id } = params;
322
- const collection = await this.getCollection();
406
+ async deleteVector({ id }) {
407
+ try {
408
+ const collection = await this.getCollection();
409
+ try {
410
+ await collection.get(id);
411
+ } catch (err) {
412
+ if (err.code === 13 || err.message?.includes("document not found")) {
413
+ throw new Error(`Vector with id ${id} does not exist`);
414
+ }
415
+ throw err;
416
+ }
417
+ await collection.remove(id);
418
+ } catch (error) {
419
+ throw new MastraError(
420
+ {
421
+ id: "COUCHBASE_VECTOR_DELETE_FAILED",
422
+ domain: ErrorDomain.STORAGE,
423
+ category: ErrorCategory.THIRD_PARTY,
424
+ details: {
425
+ id
426
+ }
427
+ },
428
+ error
429
+ );
430
+ }
431
+ }
432
+ async disconnect() {
323
433
  try {
324
- await collection.get(id);
325
- } catch (err) {
326
- if (err.code === 13 || err.message?.includes("document not found")) {
327
- throw new Error(`Vector with id ${id} does not exist`);
434
+ if (!this.cluster) {
435
+ return;
328
436
  }
329
- throw err;
437
+ await this.cluster.close();
438
+ } catch (error) {
439
+ throw new MastraError(
440
+ {
441
+ id: "COUCHBASE_VECTOR_DISCONNECT_FAILED",
442
+ domain: ErrorDomain.STORAGE,
443
+ category: ErrorCategory.THIRD_PARTY
444
+ },
445
+ error
446
+ );
330
447
  }
331
- await collection.remove(id);
332
448
  }
333
449
  };
334
450
 
335
451
  export { CouchbaseVector, DISTANCE_MAPPING };
452
+ //# sourceMappingURL=index.js.map
453
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vector/index.ts"],"names":[],"mappings":";;;;;AAkBO,IAAM,gBAAA,GAA0D;AAAA,EACrE,MAAA,EAAQ,QAAA;AAAA,EACR,SAAA,EAAW,SAAA;AAAA,EACX,UAAA,EAAY;AACd;AAWO,IAAM,eAAA,GAAN,cAA8B,YAAA,CAAa;AAAA,EACxC,cAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EACA,cAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA,gBAAA;AAAA,EAER,WAAA,CAAY,EAAE,gBAAA,EAAkB,QAAA,EAAU,UAAU,UAAA,EAAY,SAAA,EAAW,gBAAe,EAA0B;AAClH,IAAA,KAAA,EAAM;AAEN,IAAA,IAAI;AACF,MAAA,MAAM,kBAAA,GAAqB,QAAQ,gBAAA,EAAkB;AAAA,QACnD,QAAA;AAAA,QACA,QAAA;AAAA,QACA,aAAA,EAAe;AAAA,OAChB,CAAA;AAED,MAAA,MAAM,SAAA,GAAY,KAAK,cAAA,EAAe;AACtC,MAAA,IAAA,CAAK,cAAA,GACH,SAAA,EAAW,UAAA,CAAW,kBAAA,EAAoB;AAAA,QACxC,cAAA,EAAgB,kBAAA;AAAA,QAChB,UAAA,EAAY;AAAA,UAC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AAAA,OACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAA,GAAa;AACjB,IAAA,IAAI;AACF,MAAA,IAAI,CAAC,KAAK,OAAA,EAAS;AACjB,QAAA;AAAA,MACF;AACA,MAAA,MAAM,IAAA,CAAK,QAAQ,KAAA,EAAM;AAAA,IAC3B,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,oCAAA;AAAA,UACJ,QAAQ,WAAA,CAAY,OAAA;AAAA,UACpB,UAAU,aAAA,CAAc;AAAA,SAC1B;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { MastraVector } from '@mastra/core/vector';\nimport type {\n QueryResult,\n IndexStats,\n CreateIndexParams,\n UpsertVectorParams,\n QueryVectorParams,\n DescribeIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n UpdateVectorParams,\n} from '@mastra/core/vector';\nimport type { Bucket, Cluster, Collection, Scope } from 'couchbase';\nimport { MutateInSpec, connect, SearchRequest, VectorQuery, VectorSearch } from 'couchbase';\n\ntype MastraMetric = 'cosine' | 'euclidean' | 'dotproduct';\ntype CouchbaseMetric = 'cosine' | 'l2_norm' | 'dot_product';\nexport const DISTANCE_MAPPING: Record<MastraMetric, CouchbaseMetric> = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n};\n\nexport type CouchbaseVectorParams = {\n connectionString: string;\n username: string;\n password: string;\n bucketName: string;\n scopeName: string;\n collectionName: string;\n};\n\nexport class CouchbaseVector extends MastraVector {\n private clusterPromise: Promise<Cluster>;\n private cluster: Cluster;\n private bucketName: string;\n private collectionName: string;\n private scopeName: string;\n private collection: Collection;\n private bucket: Bucket;\n private scope: Scope;\n private vector_dimension: number;\n\n constructor({ connectionString, username, password, bucketName, scopeName, collectionName }: CouchbaseVectorParams) {\n super();\n\n try {\n const baseClusterPromise = connect(connectionString, {\n username,\n password,\n configProfile: 'wanDevelopment',\n });\n\n const telemetry = this.__getTelemetry();\n this.clusterPromise =\n telemetry?.traceClass(baseClusterPromise, {\n spanNamePrefix: 'couchbase-vector',\n attributes: {\n 'vector.type': 'couchbase',\n },\n }) ?? baseClusterPromise;\n this.cluster = null as unknown as Cluster;\n this.bucketName = bucketName;\n this.collectionName = collectionName;\n this.scopeName = scopeName;\n this.collection = null as unknown as Collection;\n this.bucket = null as unknown as Bucket;\n this.scope = null as unknown as Scope;\n this.vector_dimension = null as unknown as number;\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_INITIALIZE_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n connectionString,\n username,\n password,\n bucketName,\n scopeName,\n collectionName,\n },\n },\n error,\n );\n }\n }\n\n async getCollection() {\n if (!this.cluster) {\n this.cluster = await this.clusterPromise;\n }\n\n if (!this.collection) {\n this.bucket = this.cluster.bucket(this.bucketName);\n this.scope = this.bucket.scope(this.scopeName);\n this.collection = this.scope.collection(this.collectionName);\n }\n\n return this.collection;\n }\n\n async createIndex({ indexName, dimension, metric = 'dotproduct' as MastraMetric }: CreateIndexParams): Promise<void> {\n try {\n await this.getCollection();\n\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new Error('Dimension must be a positive integer');\n }\n\n await this.scope.searchIndexes().upsertIndex({\n name: indexName,\n sourceName: this.bucketName,\n type: 'fulltext-index',\n params: {\n doc_config: {\n docid_prefix_delim: '',\n docid_regexp: '',\n mode: 'scope.collection.type_field',\n type_field: 'type',\n },\n mapping: {\n default_analyzer: 'standard',\n default_datetime_parser: 'dateTimeOptional',\n default_field: '_all',\n default_mapping: {\n dynamic: true,\n enabled: false,\n },\n default_type: '_default',\n docvalues_dynamic: true, // [Doc](https://docs.couchbase.com/server/current/search/search-index-params.html#params) mentions this attribute is required for vector search to return the indexed field\n index_dynamic: true,\n store_dynamic: true, // [Doc](https://docs.couchbase.com/server/current/search/search-index-params.html#params) mentions this attribute is required for vector search to return the indexed field\n type_field: '_type',\n types: {\n [`${this.scopeName}.${this.collectionName}`]: {\n dynamic: true,\n enabled: true,\n properties: {\n embedding: {\n enabled: true,\n fields: [\n {\n dims: dimension,\n index: true,\n name: 'embedding',\n similarity: DISTANCE_MAPPING[metric],\n type: 'vector',\n vector_index_optimized_for: 'recall',\n store: true, // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields\n docvalues: true, // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields\n include_term_vectors: true, // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields\n },\n ],\n },\n content: {\n enabled: true,\n fields: [\n {\n index: true,\n name: 'content',\n store: true,\n type: 'text',\n },\n ],\n },\n },\n },\n },\n },\n store: {\n indexType: 'scorch',\n segmentVersion: 16,\n },\n },\n sourceUuid: '',\n sourceParams: {},\n sourceType: 'gocbcore',\n planParams: {\n maxPartitionsPerPIndex: 64,\n indexPartitions: 16,\n numReplicas: 0,\n },\n });\n this.vector_dimension = dimension;\n } catch (error: any) {\n // Check for 'already exists' error (Couchbase may throw a 400 or 409, or have a message)\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('index exists')) {\n // Fetch index info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_CREATE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n dimension,\n metric,\n },\n },\n error,\n );\n }\n }\n\n async upsert({ vectors, metadata, ids }: UpsertVectorParams): Promise<string[]> {\n try {\n await this.getCollection();\n\n if (!vectors || vectors.length === 0) {\n throw new Error('No vectors provided');\n }\n if (this.vector_dimension) {\n for (const vector of vectors) {\n if (!vector || this.vector_dimension !== vector.length) {\n throw new Error('Vector dimension mismatch');\n }\n }\n }\n\n const pointIds = ids || vectors.map(() => crypto.randomUUID());\n const records = vectors.map((vector, i) => {\n const metadataObj = metadata?.[i] || {};\n const record: Record<string, any> = {\n embedding: vector,\n metadata: metadataObj,\n };\n // If metadata has a text field, save it as content\n if (metadataObj.text) {\n record.content = metadataObj.text;\n }\n return record;\n });\n\n const allPromises = [];\n for (let i = 0; i < records.length; i++) {\n allPromises.push(this.collection.upsert(pointIds[i]!, records[i]));\n }\n await Promise.all(allPromises);\n\n return pointIds;\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_UPSERT_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n async query({ indexName, queryVector, topK = 10, includeVector = false }: QueryVectorParams): Promise<QueryResult[]> {\n try {\n await this.getCollection();\n\n const index_stats = await this.describeIndex({ indexName });\n if (queryVector.length !== index_stats.dimension) {\n throw new Error(\n `Query vector dimension mismatch. Expected ${index_stats.dimension}, got ${queryVector.length}`,\n );\n }\n\n let request = SearchRequest.create(\n VectorSearch.fromVectorQuery(VectorQuery.create('embedding', queryVector).numCandidates(topK)),\n );\n const results = await this.scope.search(indexName, request, {\n fields: ['*'],\n });\n\n if (includeVector) {\n throw new Error('Including vectors in search results is not yet supported by the Couchbase vector store');\n }\n const output = [];\n for (const match of results.rows) {\n const cleanedMetadata: Record<string, any> = {};\n const fields = (match.fields as Record<string, any>) || {}; // Ensure fields is an object\n for (const key in fields) {\n if (Object.prototype.hasOwnProperty.call(fields, key)) {\n const newKey = key.startsWith('metadata.') ? key.substring('metadata.'.length) : key;\n cleanedMetadata[newKey] = fields[key];\n }\n }\n output.push({\n id: match.id as string,\n score: (match.score as number) || 0,\n metadata: cleanedMetadata, // Use the cleaned metadata object\n });\n }\n return output;\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_QUERY_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n topK,\n },\n },\n error,\n );\n }\n }\n\n async listIndexes(): Promise<string[]> {\n try {\n await this.getCollection();\n const indexes = await this.scope.searchIndexes().getAllIndexes();\n return indexes?.map(index => index.name) || [];\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_LIST_INDEXES_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n try {\n await this.getCollection();\n if (!(await this.listIndexes()).includes(indexName)) {\n throw new Error(`Index ${indexName} does not exist`);\n }\n const index = await this.scope.searchIndexes().getIndex(indexName);\n const dimensions =\n index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]\n ?.dims;\n const count = -1; // Not added support yet for adding a count of documents covered by an index\n const metric = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding\n ?.fields?.[0]?.similarity as CouchbaseMetric;\n return {\n dimension: dimensions,\n count: count,\n metric: Object.keys(DISTANCE_MAPPING).find(\n key => DISTANCE_MAPPING[key as MastraMetric] === metric,\n ) as MastraMetric,\n };\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_DESCRIBE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n },\n },\n error,\n );\n }\n }\n\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.getCollection();\n if (!(await this.listIndexes()).includes(indexName)) {\n throw new Error(`Index ${indexName} does not exist`);\n }\n await this.scope.searchIndexes().dropIndex(indexName);\n this.vector_dimension = null as unknown as number;\n } catch (error) {\n if (error instanceof MastraError) {\n throw error;\n }\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_DELETE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates a vector by its ID with the provided vector and/or metadata.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to update.\n * @param update - An object containing the vector and/or metadata to update.\n * @param update.vector - An optional array of numbers representing the new vector.\n * @param update.metadata - An optional record containing the new metadata.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector({ id, update }: UpdateVectorParams): Promise<void> {\n try {\n if (!update.vector && !update.metadata) {\n throw new Error('No updates provided');\n }\n if (update.vector && this.vector_dimension && update.vector.length !== this.vector_dimension) {\n throw new Error('Vector dimension mismatch');\n }\n const collection = await this.getCollection();\n\n // Check if document exists\n try {\n await collection.get(id);\n } catch (err: any) {\n if (err.code === 13 || err.message?.includes('document not found')) {\n throw new Error(`Vector with id ${id} does not exist`);\n }\n throw err;\n }\n\n const specs: MutateInSpec[] = [];\n if (update.vector) specs.push(MutateInSpec.replace('embedding', update.vector));\n if (update.metadata) specs.push(MutateInSpec.replace('metadata', update.metadata));\n\n await collection.mutateIn(id, specs);\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_UPDATE_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n id,\n hasVectorUpdate: !!update.vector,\n hasMetadataUpdate: !!update.metadata,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Deletes a vector by its ID.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to delete.\n * @returns A promise that resolves when the deletion is complete.\n * @throws Will throw an error if the deletion operation fails.\n */\n async deleteVector({ id }: DeleteVectorParams): Promise<void> {\n try {\n const collection = await this.getCollection();\n\n // Check if document exists\n try {\n await collection.get(id);\n } catch (err: any) {\n if (err.code === 13 || err.message?.includes('document not found')) {\n throw new Error(`Vector with id ${id} does not exist`);\n }\n throw err;\n }\n\n await collection.remove(id);\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_DELETE_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n id,\n },\n },\n error,\n );\n }\n }\n\n async disconnect() {\n try {\n if (!this.cluster) {\n return;\n }\n await this.cluster.close();\n } catch (error) {\n throw new MastraError(\n {\n id: 'COUCHBASE_VECTOR_DISCONNECT_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n}\n"]}
@@ -0,0 +1,61 @@
1
+ import { MastraVector } from '@mastra/core/vector';
2
+ import type { QueryResult, IndexStats, CreateIndexParams, UpsertVectorParams, QueryVectorParams, DescribeIndexParams, DeleteIndexParams, DeleteVectorParams, UpdateVectorParams } from '@mastra/core/vector';
3
+ import type { Collection } from 'couchbase';
4
+ type MastraMetric = 'cosine' | 'euclidean' | 'dotproduct';
5
+ type CouchbaseMetric = 'cosine' | 'l2_norm' | 'dot_product';
6
+ export declare const DISTANCE_MAPPING: Record<MastraMetric, CouchbaseMetric>;
7
+ export type CouchbaseVectorParams = {
8
+ connectionString: string;
9
+ username: string;
10
+ password: string;
11
+ bucketName: string;
12
+ scopeName: string;
13
+ collectionName: string;
14
+ };
15
+ export declare class CouchbaseVector extends MastraVector {
16
+ private clusterPromise;
17
+ private cluster;
18
+ private bucketName;
19
+ private collectionName;
20
+ private scopeName;
21
+ private collection;
22
+ private bucket;
23
+ private scope;
24
+ private vector_dimension;
25
+ constructor({ connectionString, username, password, bucketName, scopeName, collectionName }: CouchbaseVectorParams);
26
+ getCollection(): Promise<Collection>;
27
+ createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
28
+ upsert({ vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
29
+ query({ indexName, queryVector, topK, includeVector }: QueryVectorParams): Promise<QueryResult[]>;
30
+ listIndexes(): Promise<string[]>;
31
+ /**
32
+ * Retrieves statistics about a vector index.
33
+ *
34
+ * @param {string} indexName - The name of the index to describe
35
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
36
+ */
37
+ describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats>;
38
+ deleteIndex({ indexName }: DeleteIndexParams): Promise<void>;
39
+ /**
40
+ * Updates a vector by its ID with the provided vector and/or metadata.
41
+ * @param indexName - The name of the index containing the vector.
42
+ * @param id - The ID of the vector to update.
43
+ * @param update - An object containing the vector and/or metadata to update.
44
+ * @param update.vector - An optional array of numbers representing the new vector.
45
+ * @param update.metadata - An optional record containing the new metadata.
46
+ * @returns A promise that resolves when the update is complete.
47
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
48
+ */
49
+ updateVector({ id, update }: UpdateVectorParams): Promise<void>;
50
+ /**
51
+ * Deletes a vector by its ID.
52
+ * @param indexName - The name of the index containing the vector.
53
+ * @param id - The ID of the vector to delete.
54
+ * @returns A promise that resolves when the deletion is complete.
55
+ * @throws Will throw an error if the deletion operation fails.
56
+ */
57
+ deleteVector({ id }: DeleteVectorParams): Promise<void>;
58
+ disconnect(): Promise<void>;
59
+ }
60
+ export {};
61
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vector/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAmB,UAAU,EAAS,MAAM,WAAW,CAAC;AAGpE,KAAK,YAAY,GAAG,QAAQ,GAAG,WAAW,GAAG,YAAY,CAAC;AAC1D,KAAK,eAAe,GAAG,QAAQ,GAAG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