@mastra/qdrant 0.0.0-error-handler-fix-20251020202607 → 0.0.0-execa-dynamic-import-20260304221256

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,5 +1,6 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraVector } from '@mastra/core/vector';
2
+ import { createVectorErrorId } from '@mastra/core/storage';
3
+ import { MastraVector, validateUpsertInput } from '@mastra/core/vector';
3
4
  import { QdrantClient } from '@qdrant/js-client-rest';
4
5
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
5
6
 
@@ -12,11 +13,15 @@ var QdrantFilterTranslator = class extends BaseFilterTranslator {
12
13
  return {
13
14
  ...BaseFilterTranslator.DEFAULT_OPERATORS,
14
15
  logical: ["$and", "$or", "$not"],
15
- array: ["$in", "$nin"],
16
+ array: ["$in", "$nin", "$all"],
16
17
  regex: ["$regex"],
18
+ element: ["$exists"],
17
19
  custom: ["$count", "$geo", "$nested", "$datetime", "$null", "$empty", "$hasId", "$hasVector"]
18
20
  };
19
21
  }
22
+ isOperator(key) {
23
+ return super.isOperator(key) || key === "$not";
24
+ }
20
25
  translate(filter) {
21
26
  if (this.isEmpty(filter)) return filter;
22
27
  this.validateFilter(filter);
@@ -43,7 +48,7 @@ var QdrantFilterTranslator = class extends BaseFilterTranslator {
43
48
  return node.length === 0 ? { is_empty: { key: fieldKey } } : this.createCondition("match", { any: this.normalizeArrayValues(node) }, fieldKey);
44
49
  }
45
50
  const entries = Object.entries(node);
46
- const logicalResult = this.handleLogicalOperators(entries, isNested);
51
+ const logicalResult = this.handleLogicalOperators(entries, isNested, fieldKey);
47
52
  if (logicalResult) {
48
53
  return logicalResult;
49
54
  }
@@ -65,8 +70,11 @@ var QdrantFilterTranslator = class extends BaseFilterTranslator {
65
70
  return { must: conditions };
66
71
  }
67
72
  }
68
- handleLogicalOperators(entries, isNested) {
73
+ handleLogicalOperators(entries, isNested, fieldKey) {
69
74
  const firstKey = entries[0]?.[0];
75
+ if (firstKey === "$not" && fieldKey) {
76
+ return null;
77
+ }
70
78
  if (firstKey && this.isLogicalOperator(firstKey) && !this.isCustomOperator(firstKey)) {
71
79
  const [key, value] = entries[0];
72
80
  const qdrantOp = this.getQdrantLogicalOp(key);
@@ -91,7 +99,34 @@ var QdrantFilterTranslator = class extends BaseFilterTranslator {
91
99
  conditions.push(customOp);
92
100
  } else if (this.isOperator(key)) {
93
101
  const opResult = this.translateOperatorValue(key, value);
94
- if (opResult.range) {
102
+ if (opResult._specialNull) {
103
+ conditions.push({ is_null: { key: fieldKey } });
104
+ } else if (opResult._specialNotNull) {
105
+ conditions.push({ must_not: [{ is_null: { key: fieldKey } }] });
106
+ } else if (opResult._specialNe) {
107
+ conditions.push({
108
+ must_not: [{ key: fieldKey, match: { value: opResult._specialNe } }]
109
+ });
110
+ } else if (opResult._specialNin) {
111
+ conditions.push({
112
+ must_not: [{ key: fieldKey, match: { any: opResult._specialNin } }]
113
+ });
114
+ } else if (opResult._specialAll) {
115
+ for (const val of opResult._specialAll) {
116
+ conditions.push({ key: fieldKey, match: { value: val } });
117
+ }
118
+ } else if (opResult._specialExists) {
119
+ conditions.push({
120
+ must_not: [{ is_null: { key: fieldKey } }, { is_empty: { key: fieldKey } }]
121
+ });
122
+ } else if (opResult._specialNotExists) {
123
+ conditions.push({
124
+ should: [{ is_null: { key: fieldKey } }, { is_empty: { key: fieldKey } }]
125
+ });
126
+ } else if (opResult._specialNot) {
127
+ const innerResult = this.translateNode(opResult._specialNot, true, fieldKey);
128
+ conditions.push({ must_not: [innerResult] });
129
+ } else if (opResult.range) {
95
130
  Object.assign(range, opResult.range);
96
131
  } else {
97
132
  matchCondition = opResult;
@@ -162,9 +197,15 @@ var QdrantFilterTranslator = class extends BaseFilterTranslator {
162
197
  const normalizedValue = this.normalizeComparisonValue(value);
163
198
  switch (operator) {
164
199
  case "$eq":
200
+ if (value === null) {
201
+ return { _specialNull: true };
202
+ }
165
203
  return { value: normalizedValue };
166
204
  case "$ne":
167
- return { except: [normalizedValue] };
205
+ if (value === null) {
206
+ return { _specialNotNull: true };
207
+ }
208
+ return { _specialNe: normalizedValue };
168
209
  case "$gt":
169
210
  return { range: { gt: normalizedValue } };
170
211
  case "$gte":
@@ -176,15 +217,15 @@ var QdrantFilterTranslator = class extends BaseFilterTranslator {
176
217
  case "$in":
177
218
  return { any: this.normalizeArrayValues(value) };
178
219
  case "$nin":
179
- return { except: this.normalizeArrayValues(value) };
220
+ return { _specialNin: this.normalizeArrayValues(value) };
180
221
  case "$regex":
181
222
  return { text: value };
182
- case "exists":
183
- return value ? {
184
- must_not: [{ is_null: { key: value } }, { is_empty: { key: value } }]
185
- } : {
186
- is_empty: { key: value }
187
- };
223
+ case "$all":
224
+ return { _specialAll: this.normalizeArrayValues(value) };
225
+ case "$exists":
226
+ return value ? { _specialExists: true } : { _specialNotExists: true };
227
+ case "$not":
228
+ return { _specialNot: value };
188
229
  default:
189
230
  throw new Error(`Unsupported operator: ${operator}`);
190
231
  }
@@ -240,38 +281,64 @@ var QdrantVector = class extends MastraVector {
240
281
  client;
241
282
  /**
242
283
  * Creates a new QdrantVector client.
284
+ * @param id - The unique identifier for this vector store instance.
243
285
  * @param url - The URL of the Qdrant server.
244
286
  * @param apiKey - The API key for Qdrant.
245
287
  * @param https - Whether to use HTTPS.
246
288
  */
247
- constructor({ url, apiKey, https, ...rest }) {
248
- super();
249
- const baseClient = new QdrantClient({
250
- url,
251
- apiKey,
252
- https,
253
- ...rest
254
- });
255
- const telemetry = this.__getTelemetry();
256
- this.client = telemetry?.traceClass(baseClient, {
257
- spanNamePrefix: "qdrant-vector",
258
- attributes: {
259
- "vector.type": "qdrant"
260
- }
261
- }) ?? baseClient;
289
+ constructor({ id, ...qdrantParams }) {
290
+ super({ id });
291
+ this.client = new QdrantClient(qdrantParams);
292
+ }
293
+ /**
294
+ * Validates that a named vector exists in the collection.
295
+ * @param indexName - The name of the collection to check.
296
+ * @param vectorName - The name of the vector space to validate.
297
+ * @throws Error if the vector name doesn't exist in the collection.
298
+ */
299
+ async validateVectorName(indexName, vectorName) {
300
+ const { config } = await this.client.getCollection(indexName);
301
+ const vectorsConfig = config.params.vectors;
302
+ const isNamedVectors = vectorsConfig && typeof vectorsConfig === "object" && !("size" in vectorsConfig);
303
+ if (!isNamedVectors || !(vectorName in vectorsConfig)) {
304
+ throw new Error(`Vector name "${vectorName}" does not exist in collection "${indexName}"`);
305
+ }
262
306
  }
263
- async upsert({ indexName, vectors, metadata, ids }) {
307
+ /**
308
+ * Upserts vectors into the index.
309
+ * @param indexName - The name of the index to upsert into.
310
+ * @param vectors - Array of embedding vectors.
311
+ * @param metadata - Optional metadata for each vector.
312
+ * @param ids - Optional vector IDs (auto-generated if not provided).
313
+ * @param vectorName - Optional name of the vector space when using named vectors.
314
+ */
315
+ async upsert({ indexName, vectors, metadata, ids, vectorName }) {
316
+ validateUpsertInput("QDRANT", vectors, metadata, ids);
264
317
  const pointIds = ids || vectors.map(() => crypto.randomUUID());
318
+ if (vectorName) {
319
+ try {
320
+ await this.validateVectorName(indexName, vectorName);
321
+ } catch (validationError) {
322
+ throw new MastraError(
323
+ {
324
+ id: createVectorErrorId("QDRANT", "UPSERT", "INVALID_VECTOR_NAME"),
325
+ domain: ErrorDomain.STORAGE,
326
+ category: ErrorCategory.USER,
327
+ details: { indexName, vectorName }
328
+ },
329
+ validationError
330
+ );
331
+ }
332
+ }
265
333
  const records = vectors.map((vector, i) => ({
266
334
  id: pointIds[i],
267
- vector,
335
+ vector: vectorName ? { [vectorName]: vector } : vector,
268
336
  payload: metadata?.[i] || {}
269
337
  }));
270
338
  try {
271
339
  for (let i = 0; i < records.length; i += BATCH_SIZE) {
272
340
  const batch = records.slice(i, i + BATCH_SIZE);
273
341
  await this.client.upsert(indexName, {
274
- // @ts-expect-error
275
342
  points: batch,
276
343
  wait: true
277
344
  });
@@ -280,50 +347,118 @@ var QdrantVector = class extends MastraVector {
280
347
  } catch (error) {
281
348
  throw new MastraError(
282
349
  {
283
- id: "STORAGE_QDRANT_VECTOR_UPSERT_FAILED",
350
+ id: createVectorErrorId("QDRANT", "UPSERT", "FAILED"),
284
351
  domain: ErrorDomain.STORAGE,
285
352
  category: ErrorCategory.THIRD_PARTY,
286
- details: { indexName, vectorCount: vectors.length }
353
+ details: { indexName, vectorCount: vectors.length, ...vectorName && { vectorName } }
287
354
  },
288
355
  error
289
356
  );
290
357
  }
291
358
  }
292
- async createIndex({ indexName, dimension, metric = "cosine" }) {
359
+ /**
360
+ * Creates a new index (collection) in Qdrant.
361
+ * Supports both single vector and named vector configurations.
362
+ *
363
+ * @param indexName - The name of the collection to create.
364
+ * @param dimension - Vector dimension (required for single vector mode).
365
+ * @param metric - Distance metric (default: 'cosine').
366
+ * @param namedVectors - Optional named vector configurations for multi-vector collections.
367
+ *
368
+ * @example
369
+ * ```ts
370
+ * // Single vector collection
371
+ * await qdrant.createIndex({ indexName: 'docs', dimension: 768, metric: 'cosine' });
372
+ *
373
+ * // Named vectors collection
374
+ * await qdrant.createIndex({
375
+ * indexName: 'multi-modal',
376
+ * dimension: 768, // Used as fallback, can be omitted with namedVectors
377
+ * namedVectors: {
378
+ * text: { size: 768, distance: 'cosine' },
379
+ * image: { size: 512, distance: 'euclidean' },
380
+ * },
381
+ * });
382
+ * ```
383
+ */
384
+ async createIndex({ indexName, dimension, metric = "cosine", namedVectors }) {
293
385
  try {
294
- if (!Number.isInteger(dimension) || dimension <= 0) {
295
- throw new Error("Dimension must be a positive integer");
296
- }
297
- if (!DISTANCE_MAPPING[metric]) {
298
- throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
386
+ if (namedVectors) {
387
+ if (Object.keys(namedVectors).length === 0) {
388
+ throw new Error("namedVectors must contain at least one named vector configuration");
389
+ }
390
+ for (const [name, config] of Object.entries(namedVectors)) {
391
+ if (!Number.isInteger(config.size) || config.size <= 0) {
392
+ throw new Error(`Named vector "${name}": size must be a positive integer`);
393
+ }
394
+ if (!DISTANCE_MAPPING[config.distance]) {
395
+ throw new Error(
396
+ `Named vector "${name}": invalid distance "${config.distance}". Must be one of: cosine, euclidean, dotproduct`
397
+ );
398
+ }
399
+ }
400
+ } else {
401
+ if (!Number.isInteger(dimension) || dimension <= 0) {
402
+ throw new Error("Dimension must be a positive integer");
403
+ }
404
+ if (!DISTANCE_MAPPING[metric]) {
405
+ throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
406
+ }
299
407
  }
300
408
  } catch (validationError) {
301
409
  throw new MastraError(
302
410
  {
303
- id: "STORAGE_QDRANT_VECTOR_CREATE_INDEX_INVALID_ARGS",
411
+ id: createVectorErrorId("QDRANT", "CREATE_INDEX", "INVALID_ARGS"),
304
412
  domain: ErrorDomain.STORAGE,
305
413
  category: ErrorCategory.USER,
306
- details: { indexName, dimension, metric }
414
+ details: {
415
+ indexName,
416
+ dimension,
417
+ metric,
418
+ ...namedVectors && { namedVectorNames: Object.keys(namedVectors).join(", ") }
419
+ }
307
420
  },
308
421
  validationError
309
422
  );
310
423
  }
311
424
  try {
312
- await this.client.createCollection(indexName, {
313
- vectors: {
314
- size: dimension,
315
- distance: DISTANCE_MAPPING[metric]
316
- }
317
- });
425
+ if (namedVectors) {
426
+ const namedVectorsConfig = Object.entries(namedVectors).reduce(
427
+ (acc, [name, config]) => {
428
+ acc[name] = {
429
+ size: config.size,
430
+ distance: DISTANCE_MAPPING[config.distance]
431
+ };
432
+ return acc;
433
+ },
434
+ {}
435
+ );
436
+ await this.client.createCollection(indexName, {
437
+ vectors: namedVectorsConfig
438
+ });
439
+ } else {
440
+ await this.client.createCollection(indexName, {
441
+ vectors: {
442
+ size: dimension,
443
+ distance: DISTANCE_MAPPING[metric]
444
+ }
445
+ });
446
+ }
318
447
  } catch (error) {
319
448
  const message = error?.message || error?.toString();
320
449
  if (error?.status === 409 || typeof message === "string" && message.toLowerCase().includes("exists")) {
321
- await this.validateExistingIndex(indexName, dimension, metric);
450
+ if (!namedVectors) {
451
+ await this.validateExistingIndex(indexName, dimension, metric);
452
+ } else {
453
+ this.logger.info(
454
+ `Collection "${indexName}" already exists. Skipping validation for named vectors configuration.`
455
+ );
456
+ }
322
457
  return;
323
458
  }
324
459
  throw new MastraError(
325
460
  {
326
- id: "STORAGE_QDRANT_VECTOR_CREATE_INDEX_FAILED",
461
+ id: createVectorErrorId("QDRANT", "CREATE_INDEX", "FAILED"),
327
462
  domain: ErrorDomain.STORAGE,
328
463
  category: ErrorCategory.THIRD_PARTY,
329
464
  details: { indexName, dimension, metric }
@@ -336,13 +471,33 @@ var QdrantVector = class extends MastraVector {
336
471
  const translator = new QdrantFilterTranslator();
337
472
  return translator.translate(filter);
338
473
  }
474
+ /**
475
+ * Queries the index for similar vectors.
476
+ *
477
+ * @param indexName - The name of the index to query.
478
+ * @param queryVector - The query vector to find similar vectors for.
479
+ * @param topK - Number of results to return (default: 10).
480
+ * @param filter - Optional metadata filter.
481
+ * @param includeVector - Whether to include vectors in results (default: false).
482
+ * @param using - Name of the vector space to query when using named vectors.
483
+ */
339
484
  async query({
340
485
  indexName,
341
486
  queryVector,
342
487
  topK = 10,
343
488
  filter,
344
- includeVector = false
489
+ includeVector = false,
490
+ using
345
491
  }) {
492
+ if (!queryVector) {
493
+ throw new MastraError({
494
+ id: createVectorErrorId("QDRANT", "QUERY", "MISSING_VECTOR"),
495
+ text: "queryVector is required for Qdrant queries. Metadata-only queries are not supported by this vector store.",
496
+ domain: ErrorDomain.STORAGE,
497
+ category: ErrorCategory.USER,
498
+ details: { indexName }
499
+ });
500
+ }
346
501
  const translatedFilter = this.transformFilter(filter) ?? {};
347
502
  try {
348
503
  const results = (await this.client.query(indexName, {
@@ -350,15 +505,20 @@ var QdrantVector = class extends MastraVector {
350
505
  limit: topK,
351
506
  filter: translatedFilter,
352
507
  with_payload: true,
353
- with_vector: includeVector
508
+ with_vector: includeVector,
509
+ ...using ? { using } : {}
354
510
  })).points;
355
511
  return results.map((match) => {
356
512
  let vector = [];
357
- if (includeVector) {
513
+ if (includeVector && match.vector != null) {
358
514
  if (Array.isArray(match.vector)) {
359
515
  vector = match.vector;
360
516
  } else if (typeof match.vector === "object" && match.vector !== null) {
361
- vector = Object.values(match.vector).filter((v) => typeof v === "number");
517
+ const namedVectors = match.vector;
518
+ const sourceArray = using && Array.isArray(namedVectors[using]) ? namedVectors[using] : Object.values(namedVectors).find((v) => Array.isArray(v));
519
+ if (sourceArray) {
520
+ vector = sourceArray.filter((v) => typeof v === "number");
521
+ }
362
522
  }
363
523
  }
364
524
  return {
@@ -371,10 +531,10 @@ var QdrantVector = class extends MastraVector {
371
531
  } catch (error) {
372
532
  throw new MastraError(
373
533
  {
374
- id: "STORAGE_QDRANT_VECTOR_QUERY_FAILED",
534
+ id: createVectorErrorId("QDRANT", "QUERY", "FAILED"),
375
535
  domain: ErrorDomain.STORAGE,
376
536
  category: ErrorCategory.THIRD_PARTY,
377
- details: { indexName, topK }
537
+ details: { indexName, topK, ...using && { using } }
378
538
  },
379
539
  error
380
540
  );
@@ -387,7 +547,7 @@ var QdrantVector = class extends MastraVector {
387
547
  } catch (error) {
388
548
  throw new MastraError(
389
549
  {
390
- id: "STORAGE_QDRANT_VECTOR_LIST_INDEXES_FAILED",
550
+ id: createVectorErrorId("QDRANT", "LIST_INDEXES", "FAILED"),
391
551
  domain: ErrorDomain.STORAGE,
392
552
  category: ErrorCategory.THIRD_PARTY
393
553
  },
@@ -408,13 +568,13 @@ var QdrantVector = class extends MastraVector {
408
568
  return {
409
569
  dimension: config.params.vectors?.size,
410
570
  count: points_count || 0,
411
- // @ts-expect-error
571
+ // @ts-expect-error - Object.keys returns string[] but DISTANCE_MAPPING keys are typed
412
572
  metric: Object.keys(DISTANCE_MAPPING).find((key) => DISTANCE_MAPPING[key] === distance)
413
573
  };
414
574
  } catch (error) {
415
575
  throw new MastraError(
416
576
  {
417
- id: "STORAGE_QDRANT_VECTOR_DESCRIBE_INDEX_FAILED",
577
+ id: createVectorErrorId("QDRANT", "DESCRIBE_INDEX", "FAILED"),
418
578
  domain: ErrorDomain.STORAGE,
419
579
  category: ErrorCategory.THIRD_PARTY,
420
580
  details: { indexName }
@@ -427,9 +587,14 @@ var QdrantVector = class extends MastraVector {
427
587
  try {
428
588
  await this.client.deleteCollection(indexName);
429
589
  } catch (error) {
590
+ const errorMessage = error?.message || error?.toString() || "";
591
+ if (error?.status === 404 || errorMessage.toLowerCase().includes("not found") || errorMessage.toLowerCase().includes("not exist")) {
592
+ this.logger.info(`Collection ${indexName} does not exist, treating as already deleted`);
593
+ return;
594
+ }
430
595
  throw new MastraError(
431
596
  {
432
- id: "STORAGE_QDRANT_VECTOR_DELETE_INDEX_FAILED",
597
+ id: createVectorErrorId("QDRANT", "DELETE_INDEX", "FAILED"),
433
598
  domain: ErrorDomain.STORAGE,
434
599
  category: ErrorCategory.THIRD_PARTY,
435
600
  details: { indexName }
@@ -439,66 +604,143 @@ var QdrantVector = class extends MastraVector {
439
604
  }
440
605
  }
441
606
  /**
442
- * Updates a vector by its ID with the provided vector and/or metadata.
443
- * @param indexName - The name of the index containing the vector.
444
- * @param id - The ID of the vector to update.
607
+ * Updates a vector by its ID or multiple vectors matching a filter.
608
+ * @param indexName - The name of the index containing the vector(s).
609
+ * @param id - The ID of the vector to update (mutually exclusive with filter).
610
+ * @param filter - Filter to match multiple vectors to update (mutually exclusive with id).
445
611
  * @param update - An object containing the vector and/or metadata to update.
446
612
  * @param update.vector - An optional array of numbers representing the new vector.
447
613
  * @param update.metadata - An optional record containing the new metadata.
448
614
  * @returns A promise that resolves when the update is complete.
449
615
  * @throws Will throw an error if no updates are provided or if the update operation fails.
450
616
  */
451
- async updateVector({ indexName, id, update }) {
452
- try {
453
- if (!update.vector && !update.metadata) {
454
- throw new Error("No updates provided");
455
- }
456
- } catch (validationError) {
457
- throw new MastraError(
458
- {
459
- id: "STORAGE_QDRANT_VECTOR_UPDATE_VECTOR_INVALID_ARGS",
460
- domain: ErrorDomain.STORAGE,
461
- category: ErrorCategory.USER,
462
- details: { indexName, id }
463
- },
464
- validationError
465
- );
617
+ async updateVector({ indexName, id, filter, update }) {
618
+ if (id && filter) {
619
+ throw new MastraError({
620
+ id: createVectorErrorId("QDRANT", "UPDATE_VECTOR", "MUTUALLY_EXCLUSIVE"),
621
+ text: "Cannot specify both id and filter - they are mutually exclusive",
622
+ domain: ErrorDomain.STORAGE,
623
+ category: ErrorCategory.USER,
624
+ details: { indexName }
625
+ });
626
+ }
627
+ if (!id && !filter) {
628
+ throw new MastraError({
629
+ id: createVectorErrorId("QDRANT", "UPDATE_VECTOR", "NO_TARGET"),
630
+ text: "Either id or filter must be provided",
631
+ domain: ErrorDomain.STORAGE,
632
+ category: ErrorCategory.USER,
633
+ details: { indexName }
634
+ });
635
+ }
636
+ if (!update.vector && !update.metadata) {
637
+ throw new MastraError({
638
+ id: createVectorErrorId("QDRANT", "UPDATE_VECTOR", "NO_PAYLOAD"),
639
+ text: "No updates provided",
640
+ domain: ErrorDomain.STORAGE,
641
+ category: ErrorCategory.USER,
642
+ details: {
643
+ indexName,
644
+ ...id && { id }
645
+ }
646
+ });
647
+ }
648
+ if (filter && Object.keys(filter).length === 0) {
649
+ throw new MastraError({
650
+ id: createVectorErrorId("QDRANT", "UPDATE_VECTOR", "EMPTY_FILTER"),
651
+ text: "Filter cannot be an empty filter object",
652
+ domain: ErrorDomain.STORAGE,
653
+ category: ErrorCategory.USER,
654
+ details: { indexName }
655
+ });
466
656
  }
467
- const pointId = this.parsePointId(id);
468
657
  try {
469
- if (update.metadata && !update.vector) {
470
- await this.client.setPayload(indexName, { payload: update.metadata, points: [pointId] });
471
- return;
472
- }
473
- if (update.vector && !update.metadata) {
474
- await this.client.updateVectors(indexName, {
475
- points: [
476
- {
477
- id: pointId,
478
- vector: update.vector
479
- }
480
- ]
481
- });
482
- return;
483
- }
484
- if (update.vector && update.metadata) {
485
- const point = {
486
- id: pointId,
487
- vector: update.vector,
488
- payload: update.metadata
489
- };
490
- await this.client.upsert(indexName, {
491
- points: [point]
492
- });
493
- return;
658
+ if (id) {
659
+ const pointId = this.parsePointId(id);
660
+ if (update.metadata && !update.vector) {
661
+ await this.client.setPayload(indexName, { payload: update.metadata, points: [pointId] });
662
+ return;
663
+ }
664
+ if (update.vector && !update.metadata) {
665
+ await this.client.updateVectors(indexName, {
666
+ points: [
667
+ {
668
+ id: pointId,
669
+ vector: update.vector
670
+ }
671
+ ]
672
+ });
673
+ return;
674
+ }
675
+ if (update.vector && update.metadata) {
676
+ const point = {
677
+ id: pointId,
678
+ vector: update.vector,
679
+ payload: update.metadata
680
+ };
681
+ await this.client.upsert(indexName, {
682
+ points: [point]
683
+ });
684
+ return;
685
+ }
686
+ } else if (filter) {
687
+ const translatedFilter = this.transformFilter(filter);
688
+ const matchingPoints = [];
689
+ let offset = void 0;
690
+ do {
691
+ const scrollResult = await this.client.scroll(indexName, {
692
+ filter: translatedFilter,
693
+ limit: 100,
694
+ offset,
695
+ with_payload: false,
696
+ with_vector: update.vector ? false : true
697
+ // Only fetch vectors if not updating them
698
+ });
699
+ matchingPoints.push(
700
+ ...scrollResult.points.map((point) => ({
701
+ id: point.id,
702
+ vector: Array.isArray(point.vector) ? point.vector : void 0
703
+ }))
704
+ );
705
+ const nextOffset = scrollResult.next_page_offset;
706
+ offset = typeof nextOffset === "string" || typeof nextOffset === "number" ? nextOffset : void 0;
707
+ } while (offset !== void 0);
708
+ if (matchingPoints.length === 0) {
709
+ return;
710
+ }
711
+ const pointIds = matchingPoints.map((p) => p.id);
712
+ if (update.metadata && !update.vector) {
713
+ await this.client.setPayload(indexName, { payload: update.metadata, points: pointIds });
714
+ return;
715
+ }
716
+ if (update.vector) {
717
+ const points = matchingPoints.map((p) => ({
718
+ id: p.id,
719
+ vector: update.vector,
720
+ payload: update.metadata || {}
721
+ }));
722
+ for (let i = 0; i < points.length; i += BATCH_SIZE) {
723
+ const batch = points.slice(i, i + BATCH_SIZE);
724
+ await this.client.upsert(indexName, {
725
+ points: batch,
726
+ wait: true
727
+ });
728
+ }
729
+ return;
730
+ }
494
731
  }
495
732
  } catch (error) {
733
+ if (error instanceof MastraError) throw error;
496
734
  throw new MastraError(
497
735
  {
498
- id: "STORAGE_QDRANT_VECTOR_UPDATE_VECTOR_FAILED",
736
+ id: createVectorErrorId("QDRANT", "UPDATE_VECTOR", "FAILED"),
499
737
  domain: ErrorDomain.STORAGE,
500
738
  category: ErrorCategory.THIRD_PARTY,
501
- details: { indexName, id }
739
+ details: {
740
+ indexName,
741
+ ...id && { id },
742
+ ...filter && { filter: JSON.stringify(filter) }
743
+ }
502
744
  },
503
745
  error
504
746
  );
@@ -520,10 +762,13 @@ var QdrantVector = class extends MastraVector {
520
762
  } catch (error) {
521
763
  throw new MastraError(
522
764
  {
523
- id: "STORAGE_QDRANT_VECTOR_DELETE_VECTOR_FAILED",
765
+ id: createVectorErrorId("QDRANT", "DELETE_VECTOR", "FAILED"),
524
766
  domain: ErrorDomain.STORAGE,
525
767
  category: ErrorCategory.THIRD_PARTY,
526
- details: { indexName, id }
768
+ details: {
769
+ indexName,
770
+ ...id && { id }
771
+ }
527
772
  },
528
773
  error
529
774
  );
@@ -564,6 +809,245 @@ var QdrantVector = class extends MastraVector {
564
809
  }
565
810
  return id;
566
811
  }
812
+ /**
813
+ * Deletes multiple vectors by IDs or filter.
814
+ * @param indexName - The name of the index containing the vectors.
815
+ * @param ids - Array of vector IDs to delete (mutually exclusive with filter).
816
+ * @param filter - Filter to match vectors to delete (mutually exclusive with ids).
817
+ * @returns A promise that resolves when the deletion is complete.
818
+ * @throws Will throw an error if both ids and filter are provided, or if neither is provided.
819
+ */
820
+ async deleteVectors({ indexName, filter, ids }) {
821
+ if (ids && filter) {
822
+ throw new MastraError({
823
+ id: createVectorErrorId("QDRANT", "DELETE_VECTORS", "MUTUALLY_EXCLUSIVE"),
824
+ text: "Cannot specify both ids and filter - they are mutually exclusive",
825
+ domain: ErrorDomain.STORAGE,
826
+ category: ErrorCategory.USER,
827
+ details: { indexName }
828
+ });
829
+ }
830
+ if (!ids && !filter) {
831
+ throw new MastraError({
832
+ id: createVectorErrorId("QDRANT", "DELETE_VECTORS", "NO_TARGET"),
833
+ text: "Either filter or ids must be provided",
834
+ domain: ErrorDomain.STORAGE,
835
+ category: ErrorCategory.USER,
836
+ details: { indexName }
837
+ });
838
+ }
839
+ if (ids && ids.length === 0) {
840
+ throw new MastraError({
841
+ id: createVectorErrorId("QDRANT", "DELETE_VECTORS", "EMPTY_IDS"),
842
+ text: "Cannot delete with empty ids array",
843
+ domain: ErrorDomain.STORAGE,
844
+ category: ErrorCategory.USER,
845
+ details: { indexName }
846
+ });
847
+ }
848
+ if (filter && Object.keys(filter).length === 0) {
849
+ throw new MastraError({
850
+ id: createVectorErrorId("QDRANT", "DELETE_VECTORS", "EMPTY_FILTER"),
851
+ text: "Cannot delete with empty filter object",
852
+ domain: ErrorDomain.STORAGE,
853
+ category: ErrorCategory.USER,
854
+ details: { indexName }
855
+ });
856
+ }
857
+ try {
858
+ if (ids) {
859
+ const pointIds = ids.map((id) => this.parsePointId(id));
860
+ try {
861
+ await this.client.delete(indexName, {
862
+ points: pointIds,
863
+ wait: true
864
+ });
865
+ } catch (error) {
866
+ const message = error?.message || error?.toString() || "";
867
+ if (message.toLowerCase().includes("bad request")) {
868
+ return;
869
+ }
870
+ throw error;
871
+ }
872
+ } else if (filter) {
873
+ const translatedFilter = this.transformFilter(filter) ?? {};
874
+ await this.client.delete(indexName, {
875
+ filter: translatedFilter,
876
+ wait: true
877
+ });
878
+ }
879
+ } catch (error) {
880
+ if (error instanceof MastraError) throw error;
881
+ throw new MastraError(
882
+ {
883
+ id: createVectorErrorId("QDRANT", "DELETE_VECTORS", "FAILED"),
884
+ domain: ErrorDomain.STORAGE,
885
+ category: ErrorCategory.THIRD_PARTY,
886
+ details: {
887
+ indexName,
888
+ ...filter && { filter: JSON.stringify(filter) },
889
+ ...ids && { idsCount: ids.length }
890
+ }
891
+ },
892
+ error
893
+ );
894
+ }
895
+ }
896
+ /**
897
+ * Creates a payload index on a Qdrant collection to enable efficient filtering on metadata fields.
898
+ *
899
+ * This is required for Qdrant Cloud and any Qdrant instance with `strict_mode_config = true`,
900
+ * where metadata (payload) fields must be explicitly indexed before they can be used for filtering.
901
+ *
902
+ * @param params - The parameters for creating the payload index.
903
+ * @param params.indexName - The name of the collection (index) to create the payload index on.
904
+ * @param params.fieldName - The name of the payload field to index.
905
+ * @param params.fieldSchema - The schema type for the field (e.g., 'keyword', 'integer', 'text').
906
+ * @param params.wait - Whether to wait for the operation to complete. Defaults to true.
907
+ * @returns A promise that resolves when the index is created (idempotent if index already exists).
908
+ * @throws Will throw a MastraError if arguments are invalid or if the operation fails.
909
+ *
910
+ * @example
911
+ * ```ts
912
+ * // Create a keyword index for filtering by source
913
+ * await qdrant.createPayloadIndex({
914
+ * indexName: 'my-collection',
915
+ * fieldName: 'source',
916
+ * fieldSchema: 'keyword',
917
+ * });
918
+ *
919
+ * // Create an integer index for numeric filtering
920
+ * await qdrant.createPayloadIndex({
921
+ * indexName: 'my-collection',
922
+ * fieldName: 'price',
923
+ * fieldSchema: 'integer',
924
+ * });
925
+ * ```
926
+ *
927
+ * @see https://qdrant.tech/documentation/concepts/indexing/#payload-index
928
+ */
929
+ async createPayloadIndex({
930
+ indexName,
931
+ fieldName,
932
+ fieldSchema,
933
+ wait = true
934
+ }) {
935
+ const validSchemas = [
936
+ "keyword",
937
+ "integer",
938
+ "float",
939
+ "geo",
940
+ "text",
941
+ "bool",
942
+ "datetime",
943
+ "uuid"
944
+ ];
945
+ if (!indexName || typeof indexName !== "string" || indexName.trim() === "") {
946
+ throw new MastraError({
947
+ id: createVectorErrorId("QDRANT", "CREATE_PAYLOAD_INDEX", "INVALID_ARGS"),
948
+ text: "indexName must be a non-empty string",
949
+ domain: ErrorDomain.STORAGE,
950
+ category: ErrorCategory.USER,
951
+ details: { indexName, fieldName, fieldSchema }
952
+ });
953
+ }
954
+ if (!fieldName || typeof fieldName !== "string" || fieldName.trim() === "") {
955
+ throw new MastraError({
956
+ id: createVectorErrorId("QDRANT", "CREATE_PAYLOAD_INDEX", "INVALID_ARGS"),
957
+ text: "fieldName must be a non-empty string",
958
+ domain: ErrorDomain.STORAGE,
959
+ category: ErrorCategory.USER,
960
+ details: { indexName, fieldName, fieldSchema }
961
+ });
962
+ }
963
+ if (!validSchemas.includes(fieldSchema)) {
964
+ throw new MastraError({
965
+ id: createVectorErrorId("QDRANT", "CREATE_PAYLOAD_INDEX", "INVALID_ARGS"),
966
+ text: `fieldSchema must be one of: ${validSchemas.join(", ")}`,
967
+ domain: ErrorDomain.STORAGE,
968
+ category: ErrorCategory.USER,
969
+ details: { indexName, fieldName, fieldSchema }
970
+ });
971
+ }
972
+ try {
973
+ await this.client.createPayloadIndex(indexName, {
974
+ field_name: fieldName,
975
+ field_schema: fieldSchema,
976
+ wait
977
+ });
978
+ } catch (error) {
979
+ const message = error?.message || error?.toString() || "";
980
+ if (error?.status === 409 || message.toLowerCase().includes("exists")) {
981
+ this.logger.info(`Payload index for field "${fieldName}" already exists on collection "${indexName}"`);
982
+ return;
983
+ }
984
+ throw new MastraError(
985
+ {
986
+ id: createVectorErrorId("QDRANT", "CREATE_PAYLOAD_INDEX", "FAILED"),
987
+ domain: ErrorDomain.STORAGE,
988
+ category: ErrorCategory.THIRD_PARTY,
989
+ details: { indexName, fieldName, fieldSchema }
990
+ },
991
+ error
992
+ );
993
+ }
994
+ }
995
+ /**
996
+ * Deletes a payload index from a Qdrant collection.
997
+ *
998
+ * @param params - The parameters for deleting the payload index.
999
+ * @param params.indexName - The name of the collection (index) to delete the payload index from.
1000
+ * @param params.fieldName - The name of the payload field index to delete.
1001
+ * @param params.wait - Whether to wait for the operation to complete. Defaults to true.
1002
+ * @returns A promise that resolves when the index is deleted (idempotent if index doesn't exist).
1003
+ * @throws Will throw a MastraError if the operation fails.
1004
+ *
1005
+ * @example
1006
+ * ```ts
1007
+ * await qdrant.deletePayloadIndex({
1008
+ * indexName: 'my-collection',
1009
+ * fieldName: 'source',
1010
+ * });
1011
+ * ```
1012
+ */
1013
+ async deletePayloadIndex({ indexName, fieldName, wait = true }) {
1014
+ if (!indexName || typeof indexName !== "string" || indexName.trim() === "") {
1015
+ throw new MastraError({
1016
+ id: createVectorErrorId("QDRANT", "DELETE_PAYLOAD_INDEX", "INVALID_ARGS"),
1017
+ text: "indexName must be a non-empty string",
1018
+ domain: ErrorDomain.STORAGE,
1019
+ category: ErrorCategory.USER,
1020
+ details: { indexName, fieldName }
1021
+ });
1022
+ }
1023
+ if (!fieldName || typeof fieldName !== "string" || fieldName.trim() === "") {
1024
+ throw new MastraError({
1025
+ id: createVectorErrorId("QDRANT", "DELETE_PAYLOAD_INDEX", "INVALID_ARGS"),
1026
+ text: "fieldName must be a non-empty string",
1027
+ domain: ErrorDomain.STORAGE,
1028
+ category: ErrorCategory.USER,
1029
+ details: { indexName, fieldName }
1030
+ });
1031
+ }
1032
+ try {
1033
+ await this.client.deletePayloadIndex(indexName, fieldName, { wait });
1034
+ } catch (error) {
1035
+ const message = error?.message || error?.toString() || "";
1036
+ if (error?.status === 404 || message.toLowerCase().includes("not found") || message.toLowerCase().includes("not exist")) {
1037
+ this.logger.info(`Payload index for field "${fieldName}" does not exist on collection "${indexName}"`);
1038
+ return;
1039
+ }
1040
+ throw new MastraError(
1041
+ {
1042
+ id: createVectorErrorId("QDRANT", "DELETE_PAYLOAD_INDEX", "FAILED"),
1043
+ domain: ErrorDomain.STORAGE,
1044
+ category: ErrorCategory.THIRD_PARTY,
1045
+ details: { indexName, fieldName }
1046
+ },
1047
+ error
1048
+ );
1049
+ }
1050
+ }
567
1051
  };
568
1052
 
569
1053
  // src/vector/prompt.ts