@mastra/elasticsearch 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @mastra/elasticsearch
2
2
 
3
+ ## 1.0.0-beta.3
4
+
5
+ ### Patch Changes
6
+
7
+ - Standardize error IDs across all storage and vector stores using centralized helper functions (`createStorageErrorId` and `createVectorErrorId`). This ensures consistent error ID patterns (`MASTRA_STORAGE_{STORE}_{OPERATION}_{STATUS}` and `MASTRA_VECTOR_{STORE}_{OPERATION}_{STATUS}`) across the codebase for better error tracking and debugging. ([#10913](https://github.com/mastra-ai/mastra/pull/10913))
8
+
9
+ - Updated dependencies [[`3076c67`](https://github.com/mastra-ai/mastra/commit/3076c6778b18988ae7d5c4c5c466366974b2d63f), [`85d7ee1`](https://github.com/mastra-ai/mastra/commit/85d7ee18ff4e14d625a8a30ec6656bb49804989b), [`c6c1092`](https://github.com/mastra-ai/mastra/commit/c6c1092f8fbf76109303f69e000e96fd1960c4ce), [`81dc110`](https://github.com/mastra-ai/mastra/commit/81dc11008d147cf5bdc8996ead1aa61dbdebb6fc), [`7aedb74`](https://github.com/mastra-ai/mastra/commit/7aedb74883adf66af38e270e4068fd42e7a37036), [`8f02d80`](https://github.com/mastra-ai/mastra/commit/8f02d800777397e4b45d7f1ad041988a8b0c6630), [`d7aad50`](https://github.com/mastra-ai/mastra/commit/d7aad501ce61646b76b4b511e558ac4eea9884d0), [`ce0a73a`](https://github.com/mastra-ai/mastra/commit/ce0a73abeaa75b10ca38f9e40a255a645d50ebfb), [`a02e542`](https://github.com/mastra-ai/mastra/commit/a02e542d23179bad250b044b17ff023caa61739f), [`a372c64`](https://github.com/mastra-ai/mastra/commit/a372c640ad1fd12e8f0613cebdc682fc156b4d95), [`8846867`](https://github.com/mastra-ai/mastra/commit/8846867ffa9a3746767618e314bebac08eb77d87), [`42a42cf`](https://github.com/mastra-ai/mastra/commit/42a42cf3132b9786feecbb8c13c583dce5b0e198), [`ae08bf0`](https://github.com/mastra-ai/mastra/commit/ae08bf0ebc6a4e4da992b711c4a389c32ba84cf4), [`21735a7`](https://github.com/mastra-ai/mastra/commit/21735a7ef306963554a69a89b44f06c3bcd85141), [`1d877b8`](https://github.com/mastra-ai/mastra/commit/1d877b8d7b536a251c1a7a18db7ddcf4f68d6f8b)]:
10
+ - @mastra/core@1.0.0-beta.7
11
+
3
12
  ## 1.0.0-beta.2
4
13
 
5
14
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var elasticsearch = require('@elastic/elasticsearch');
4
4
  var error = require('@mastra/core/error');
5
+ var storage = require('@mastra/core/storage');
5
6
  var vector = require('@mastra/core/vector');
6
7
  var filter = require('@mastra/core/vector/filter');
7
8
 
@@ -391,7 +392,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
391
392
  async createIndex({ indexName, dimension, metric = "cosine" }) {
392
393
  if (!Number.isInteger(dimension) || dimension <= 0) {
393
394
  throw new error.MastraError({
394
- id: "STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_INVALID_ARGS",
395
+ id: storage.createVectorErrorId("ELASTICSEARCH", "CREATE_INDEX", "INVALID_ARGS"),
395
396
  domain: error.ErrorDomain.STORAGE,
396
397
  category: error.ErrorCategory.USER,
397
398
  text: "Dimension must be a positive integer",
@@ -422,7 +423,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
422
423
  }
423
424
  throw new error.MastraError(
424
425
  {
425
- id: "STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_FAILED",
426
+ id: storage.createVectorErrorId("ELASTICSEARCH", "CREATE_INDEX", "FAILED"),
426
427
  domain: error.ErrorDomain.STORAGE,
427
428
  category: error.ErrorCategory.THIRD_PARTY,
428
429
  details: { indexName, dimension, metric }
@@ -444,7 +445,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
444
445
  } catch (error$1) {
445
446
  throw new error.MastraError(
446
447
  {
447
- id: "STORAGE_ELASTICSEARCH_VECTOR_LIST_INDEXES_FAILED",
448
+ id: storage.createVectorErrorId("ELASTICSEARCH", "LIST_INDEXES", "FAILED"),
448
449
  domain: error.ErrorDomain.STORAGE,
449
450
  category: error.ErrorCategory.THIRD_PARTY
450
451
  },
@@ -463,7 +464,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
463
464
  } catch (infoError) {
464
465
  const mastraError = new error.MastraError(
465
466
  {
466
- id: "STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_FETCH_FAILED",
467
+ id: storage.createVectorErrorId("ELASTICSEARCH", "VALIDATE_INDEX", "FETCH_FAILED"),
467
468
  text: `Index "${indexName}" already exists, but failed to fetch index info for dimension check.`,
468
469
  domain: error.ErrorDomain.STORAGE,
469
470
  category: error.ErrorCategory.SYSTEM,
@@ -488,7 +489,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
488
489
  }
489
490
  } else if (info) {
490
491
  const mastraError = new error.MastraError({
491
- id: "STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_DIMENSION_MISMATCH",
492
+ id: storage.createVectorErrorId("ELASTICSEARCH", "VALIDATE_INDEX", "DIMENSION_MISMATCH"),
492
493
  text: `Index "${indexName}" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,
493
494
  domain: error.ErrorDomain.STORAGE,
494
495
  category: error.ErrorCategory.USER,
@@ -533,7 +534,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
533
534
  }
534
535
  const mastraError = new error.MastraError(
535
536
  {
536
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_INDEX_FAILED",
537
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_INDEX", "FAILED"),
537
538
  domain: error.ErrorDomain.STORAGE,
538
539
  category: error.ErrorCategory.THIRD_PARTY,
539
540
  details: { indexName }
@@ -608,7 +609,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
608
609
  const failedItemDetails = failedItems.map((item) => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`).join("; ");
609
610
  const mastraError = new error.MastraError(
610
611
  {
611
- id: "STORAGE_ELASTICSEARCH_VECTOR_BULK_PARTIAL_FAILURE",
612
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPSERT", "BULK_PARTIAL_FAILURE"),
612
613
  text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,
613
614
  domain: error.ErrorDomain.STORAGE,
614
615
  category: error.ErrorCategory.THIRD_PARTY,
@@ -633,7 +634,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
633
634
  } catch (error$1) {
634
635
  throw new error.MastraError(
635
636
  {
636
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPSERT_FAILED",
637
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPSERT", "FAILED"),
637
638
  domain: error.ErrorDomain.STORAGE,
638
639
  category: error.ErrorCategory.THIRD_PARTY,
639
640
  details: { indexName, vectorCount: vectors?.length || 0 }
@@ -685,7 +686,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
685
686
  } catch (error$1) {
686
687
  throw new error.MastraError(
687
688
  {
688
- id: "STORAGE_ELASTICSEARCH_VECTOR_QUERY_FAILED",
689
+ id: storage.createVectorErrorId("ELASTICSEARCH", "QUERY", "FAILED"),
689
690
  domain: error.ErrorDomain.STORAGE,
690
691
  category: error.ErrorCategory.THIRD_PARTY,
691
692
  details: { indexName, topK }
@@ -730,7 +731,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
730
731
  const { indexName, update } = params;
731
732
  if ("id" in params && "filter" in params && params.id && params.filter) {
732
733
  throw new error.MastraError({
733
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS",
734
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "MUTUALLY_EXCLUSIVE"),
734
735
  domain: error.ErrorDomain.STORAGE,
735
736
  category: error.ErrorCategory.USER,
736
737
  text: "id and filter are mutually exclusive",
@@ -739,7 +740,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
739
740
  }
740
741
  if (!update.vector && !update.metadata) {
741
742
  throw new error.MastraError({
742
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_NO_UPDATES",
743
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "NO_UPDATES"),
743
744
  domain: error.ErrorDomain.STORAGE,
744
745
  category: error.ErrorCategory.USER,
745
746
  text: "No updates provided",
@@ -748,7 +749,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
748
749
  }
749
750
  if ("filter" in params && params.filter && Object.keys(params.filter).length === 0) {
750
751
  throw new error.MastraError({
751
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS",
752
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "EMPTY_FILTER"),
752
753
  domain: error.ErrorDomain.STORAGE,
753
754
  category: error.ErrorCategory.USER,
754
755
  text: "Cannot update with empty filter",
@@ -761,7 +762,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
761
762
  await this.updateVectorsByFilter(indexName, params.filter, update);
762
763
  } else {
763
764
  throw new error.MastraError({
764
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_MISSING_PARAMS",
765
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "NO_TARGET"),
765
766
  domain: error.ErrorDomain.STORAGE,
766
767
  category: error.ErrorCategory.USER,
767
768
  text: "Either id or filter must be provided",
@@ -788,7 +789,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
788
789
  } catch (error$1) {
789
790
  throw new error.MastraError(
790
791
  {
791
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED",
792
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "FAILED"),
792
793
  domain: error.ErrorDomain.STORAGE,
793
794
  category: error.ErrorCategory.USER,
794
795
  details: {
@@ -825,7 +826,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
825
826
  } catch (error$1) {
826
827
  throw new error.MastraError(
827
828
  {
828
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED",
829
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "FAILED"),
829
830
  domain: error.ErrorDomain.STORAGE,
830
831
  category: error.ErrorCategory.THIRD_PARTY,
831
832
  details: {
@@ -867,7 +868,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
867
868
  } catch (error$1) {
868
869
  throw new error.MastraError(
869
870
  {
870
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_BY_FILTER_FAILED",
871
+ id: storage.createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR_BY_FILTER", "FAILED"),
871
872
  domain: error.ErrorDomain.STORAGE,
872
873
  category: error.ErrorCategory.THIRD_PARTY,
873
874
  details: {
@@ -899,7 +900,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
899
900
  }
900
901
  throw new error.MastraError(
901
902
  {
902
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTOR_FAILED",
903
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_VECTOR", "FAILED"),
903
904
  domain: error.ErrorDomain.STORAGE,
904
905
  category: error.ErrorCategory.THIRD_PARTY,
905
906
  details: {
@@ -914,7 +915,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
914
915
  async deleteVectors({ indexName, filter, ids }) {
915
916
  if (ids && filter) {
916
917
  throw new error.MastraError({
917
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
918
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "MUTUALLY_EXCLUSIVE"),
918
919
  domain: error.ErrorDomain.STORAGE,
919
920
  category: error.ErrorCategory.USER,
920
921
  text: "ids and filter are mutually exclusive",
@@ -923,7 +924,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
923
924
  }
924
925
  if (!ids && !filter) {
925
926
  throw new error.MastraError({
926
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
927
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "NO_TARGET"),
927
928
  domain: error.ErrorDomain.STORAGE,
928
929
  category: error.ErrorCategory.USER,
929
930
  text: "Either filter or ids must be provided",
@@ -932,7 +933,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
932
933
  }
933
934
  if (ids && ids.length === 0) {
934
935
  throw new error.MastraError({
935
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
936
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "EMPTY_IDS"),
936
937
  domain: error.ErrorDomain.STORAGE,
937
938
  category: error.ErrorCategory.USER,
938
939
  text: "Cannot delete with empty ids array",
@@ -941,7 +942,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
941
942
  }
942
943
  if (filter && Object.keys(filter).length === 0) {
943
944
  throw new error.MastraError({
944
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
945
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "EMPTY_FILTER"),
945
946
  domain: error.ErrorDomain.STORAGE,
946
947
  category: error.ErrorCategory.USER,
947
948
  text: "Cannot delete with empty filter",
@@ -986,7 +987,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
986
987
  const failedItemDetails = failedItems.map((item) => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`).join("; ");
987
988
  const mastraError = new error.MastraError(
988
989
  {
989
- id: "STORAGE_ELASTICSEARCH_VECTOR_BULK_DELETE_PARTIAL_FAILURE",
990
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "BULK_PARTIAL_FAILURE"),
990
991
  text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,
991
992
  domain: error.ErrorDomain.STORAGE,
992
993
  category: error.ErrorCategory.THIRD_PARTY,
@@ -1019,7 +1020,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
1019
1020
  if (error$1 instanceof error.MastraError) throw error$1;
1020
1021
  throw new error.MastraError(
1021
1022
  {
1022
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_FAILED",
1023
+ id: storage.createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "FAILED"),
1023
1024
  domain: error.ErrorDomain.STORAGE,
1024
1025
  category: error.ErrorCategory.THIRD_PARTY,
1025
1026
  details: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["BaseFilterTranslator","fieldWithKeyword","MastraVector","ElasticSearchClient","MastraError","ErrorDomain","ErrorCategory","error"],"mappings":";;;;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4CA,2BAAA,CAAgD;AAAA,EAC9E,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAGA,2BAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAM,CAAA;AAAA,MAC/B,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,KAAA,EAAO,CAAC,QAAQ,CAAA;AAAA,MAChB,QAAQ;AAAC,KACX;AAAA,EACF;AAAA,EAEA,UAAU,MAAA,EAA+D;AACvE,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAO,MAAA;AACjC,IAAA,IAAA,CAAK,eAAe,MAAM,CAAA;AAC1B,IAAA,OAAO,IAAA,CAAK,cAAc,MAAM,CAAA;AAAA,EAClC;AAAA,EAEQ,cAAc,IAAA,EAAsC;AAE1D,IAAA,IAAI,KAAK,WAAA,CAAY,IAAI,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UACE,EAAA,EAAI,oDAAA;AAAA,UACJ,QAAQC,iBAAA,CAAY,OAAA;AAAA,UACpB,UAAUC,mBAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACAC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_LIST_INDEXES_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_FETCH_FAILED',\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_DIMENSION_MISMATCH',\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\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 const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_BULK_PARTIAL_FAILURE',\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPSERT_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_QUERY_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\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(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_NO_UPDATES',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_MISSING_PARAMS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_BY_FILTER_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\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({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_BULK_DELETE_PARTIAL_FAILURE',\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["BaseFilterTranslator","fieldWithKeyword","MastraVector","ElasticSearchClient","MastraError","createVectorErrorId","ErrorDomain","ErrorCategory","error"],"mappings":";;;;;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4CA,2BAAA,CAAgD;AAAA,EAC9E,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAGA,2BAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAM,CAAA;AAAA,MAC/B,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,KAAA,EAAO,CAAC,QAAQ,CAAA;AAAA,MAChB,QAAQ;AAAC,KACX;AAAA,EACF;AAAA,EAEA,UAAU,MAAA,EAA+D;AACvE,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAO,MAAA;AACjC,IAAA,IAAA,CAAK,eAAe,MAAM,CAAA;AAC1B,IAAA,OAAO,IAAA,CAAK,cAAc,MAAM,CAAA;AAAA,EAClC;AAAA,EAEQ,cAAc,IAAA,EAAsC;AAE1D,IAAA,IAAI,KAAK,WAAA,CAAY,IAAI,KAAK,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjD,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,IAA2B,CAAA;AAG1D,IAAA,MAAM,mBAAoC,EAAC;AAC3C,IAAA,MAAM,kBAAmC,EAAC;AAE1C,IAAA,OAAA,CAAQ,OAAA,CAAQ,CAAC,CAAC,GAAA,EAAK,KAAK,CAAA,KAAM;AAChC,MAAA,IAAI,IAAA,CAAK,iBAAA,CAAkB,GAAG,CAAA,EAAG;AAC/B,QAAA,gBAAA,CAAiB,IAAA,CAAK,CAAC,GAAA,EAAK,KAAK,CAAC,CAAA;AAAA,MACpC,CA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,KAAA,CAAM,WAAA,CAAY,QAAA,EAAU,CAAA;AACzC,YAAA,IAAA,CAAK,MAAA,EAAQ,eAAe,WAAW,CAAA;AAGvC,YAAA,MAAM,WAAA;AAAA,UACR;AAAA,QACF;AAAA,MACF,WAAW,MAAA,EAAQ;AAEjB,QAAA,MAAM,UAAA,GAAa,IAAI,6BAAA,EAA8B;AACrD,QAAA,MAAM,gBAAA,GAAmB,UAAA,CAAW,SAAA,CAAU,MAAM,CAAA;AAEpD,QAAA,MAAM,IAAA,CAAK,OAAO,aAAA,CAAc;AAAA,UAC9B,KAAA,EAAO,SAAA;AAAA,UACP,KAAA,EAAQ,gBAAA,IAA4B,EAAE,SAAA,EAAW,EAAC,EAAE;AAAA,UACpD,OAAA,EAAS;AAAA,SACV,CAAA;AAAA,MACH;AAAA,IACF,SAASC,OAAA,EAAO;AACd,MAAA,IAAIA,OAAA,YAAiBJ,mBAAa,MAAMI,OAAA;AACxC,MAAA,MAAM,IAAIJ,iBAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAIC,2BAAA,CAAoB,eAAA,EAAiB,gBAAA,EAAkB,QAAQ,CAAA;AAAA,UACnE,QAAQC,iBAAA,CAAY,OAAA;AAAA,UACpB,UAAUC,mBAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACAC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { createVectorErrorId } from '@mastra/core/storage';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'INVALID_ARGS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'LIST_INDEXES', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'FETCH_FAILED'),\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'DIMENSION_MISMATCH'),\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\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 const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'QUERY', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\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(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_UPDATES'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR_BY_FILTER', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\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({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_IDS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Client } from '@elastic/elasticsearch';
2
2
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
+ import { createVectorErrorId } from '@mastra/core/storage';
3
4
  import { MastraVector } from '@mastra/core/vector';
4
5
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
5
6
 
@@ -389,7 +390,7 @@ var ElasticSearchVector = class extends MastraVector {
389
390
  async createIndex({ indexName, dimension, metric = "cosine" }) {
390
391
  if (!Number.isInteger(dimension) || dimension <= 0) {
391
392
  throw new MastraError({
392
- id: "STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_INVALID_ARGS",
393
+ id: createVectorErrorId("ELASTICSEARCH", "CREATE_INDEX", "INVALID_ARGS"),
393
394
  domain: ErrorDomain.STORAGE,
394
395
  category: ErrorCategory.USER,
395
396
  text: "Dimension must be a positive integer",
@@ -420,7 +421,7 @@ var ElasticSearchVector = class extends MastraVector {
420
421
  }
421
422
  throw new MastraError(
422
423
  {
423
- id: "STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_FAILED",
424
+ id: createVectorErrorId("ELASTICSEARCH", "CREATE_INDEX", "FAILED"),
424
425
  domain: ErrorDomain.STORAGE,
425
426
  category: ErrorCategory.THIRD_PARTY,
426
427
  details: { indexName, dimension, metric }
@@ -442,7 +443,7 @@ var ElasticSearchVector = class extends MastraVector {
442
443
  } catch (error) {
443
444
  throw new MastraError(
444
445
  {
445
- id: "STORAGE_ELASTICSEARCH_VECTOR_LIST_INDEXES_FAILED",
446
+ id: createVectorErrorId("ELASTICSEARCH", "LIST_INDEXES", "FAILED"),
446
447
  domain: ErrorDomain.STORAGE,
447
448
  category: ErrorCategory.THIRD_PARTY
448
449
  },
@@ -461,7 +462,7 @@ var ElasticSearchVector = class extends MastraVector {
461
462
  } catch (infoError) {
462
463
  const mastraError = new MastraError(
463
464
  {
464
- id: "STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_FETCH_FAILED",
465
+ id: createVectorErrorId("ELASTICSEARCH", "VALIDATE_INDEX", "FETCH_FAILED"),
465
466
  text: `Index "${indexName}" already exists, but failed to fetch index info for dimension check.`,
466
467
  domain: ErrorDomain.STORAGE,
467
468
  category: ErrorCategory.SYSTEM,
@@ -486,7 +487,7 @@ var ElasticSearchVector = class extends MastraVector {
486
487
  }
487
488
  } else if (info) {
488
489
  const mastraError = new MastraError({
489
- id: "STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_DIMENSION_MISMATCH",
490
+ id: createVectorErrorId("ELASTICSEARCH", "VALIDATE_INDEX", "DIMENSION_MISMATCH"),
490
491
  text: `Index "${indexName}" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,
491
492
  domain: ErrorDomain.STORAGE,
492
493
  category: ErrorCategory.USER,
@@ -531,7 +532,7 @@ var ElasticSearchVector = class extends MastraVector {
531
532
  }
532
533
  const mastraError = new MastraError(
533
534
  {
534
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_INDEX_FAILED",
535
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_INDEX", "FAILED"),
535
536
  domain: ErrorDomain.STORAGE,
536
537
  category: ErrorCategory.THIRD_PARTY,
537
538
  details: { indexName }
@@ -606,7 +607,7 @@ var ElasticSearchVector = class extends MastraVector {
606
607
  const failedItemDetails = failedItems.map((item) => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`).join("; ");
607
608
  const mastraError = new MastraError(
608
609
  {
609
- id: "STORAGE_ELASTICSEARCH_VECTOR_BULK_PARTIAL_FAILURE",
610
+ id: createVectorErrorId("ELASTICSEARCH", "UPSERT", "BULK_PARTIAL_FAILURE"),
610
611
  text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,
611
612
  domain: ErrorDomain.STORAGE,
612
613
  category: ErrorCategory.THIRD_PARTY,
@@ -631,7 +632,7 @@ var ElasticSearchVector = class extends MastraVector {
631
632
  } catch (error) {
632
633
  throw new MastraError(
633
634
  {
634
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPSERT_FAILED",
635
+ id: createVectorErrorId("ELASTICSEARCH", "UPSERT", "FAILED"),
635
636
  domain: ErrorDomain.STORAGE,
636
637
  category: ErrorCategory.THIRD_PARTY,
637
638
  details: { indexName, vectorCount: vectors?.length || 0 }
@@ -683,7 +684,7 @@ var ElasticSearchVector = class extends MastraVector {
683
684
  } catch (error) {
684
685
  throw new MastraError(
685
686
  {
686
- id: "STORAGE_ELASTICSEARCH_VECTOR_QUERY_FAILED",
687
+ id: createVectorErrorId("ELASTICSEARCH", "QUERY", "FAILED"),
687
688
  domain: ErrorDomain.STORAGE,
688
689
  category: ErrorCategory.THIRD_PARTY,
689
690
  details: { indexName, topK }
@@ -728,7 +729,7 @@ var ElasticSearchVector = class extends MastraVector {
728
729
  const { indexName, update } = params;
729
730
  if ("id" in params && "filter" in params && params.id && params.filter) {
730
731
  throw new MastraError({
731
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS",
732
+ id: createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "MUTUALLY_EXCLUSIVE"),
732
733
  domain: ErrorDomain.STORAGE,
733
734
  category: ErrorCategory.USER,
734
735
  text: "id and filter are mutually exclusive",
@@ -737,7 +738,7 @@ var ElasticSearchVector = class extends MastraVector {
737
738
  }
738
739
  if (!update.vector && !update.metadata) {
739
740
  throw new MastraError({
740
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_NO_UPDATES",
741
+ id: createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "NO_UPDATES"),
741
742
  domain: ErrorDomain.STORAGE,
742
743
  category: ErrorCategory.USER,
743
744
  text: "No updates provided",
@@ -746,7 +747,7 @@ var ElasticSearchVector = class extends MastraVector {
746
747
  }
747
748
  if ("filter" in params && params.filter && Object.keys(params.filter).length === 0) {
748
749
  throw new MastraError({
749
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS",
750
+ id: createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "EMPTY_FILTER"),
750
751
  domain: ErrorDomain.STORAGE,
751
752
  category: ErrorCategory.USER,
752
753
  text: "Cannot update with empty filter",
@@ -759,7 +760,7 @@ var ElasticSearchVector = class extends MastraVector {
759
760
  await this.updateVectorsByFilter(indexName, params.filter, update);
760
761
  } else {
761
762
  throw new MastraError({
762
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_MISSING_PARAMS",
763
+ id: createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "NO_TARGET"),
763
764
  domain: ErrorDomain.STORAGE,
764
765
  category: ErrorCategory.USER,
765
766
  text: "Either id or filter must be provided",
@@ -786,7 +787,7 @@ var ElasticSearchVector = class extends MastraVector {
786
787
  } catch (error) {
787
788
  throw new MastraError(
788
789
  {
789
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED",
790
+ id: createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "FAILED"),
790
791
  domain: ErrorDomain.STORAGE,
791
792
  category: ErrorCategory.USER,
792
793
  details: {
@@ -823,7 +824,7 @@ var ElasticSearchVector = class extends MastraVector {
823
824
  } catch (error) {
824
825
  throw new MastraError(
825
826
  {
826
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED",
827
+ id: createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR", "FAILED"),
827
828
  domain: ErrorDomain.STORAGE,
828
829
  category: ErrorCategory.THIRD_PARTY,
829
830
  details: {
@@ -865,7 +866,7 @@ var ElasticSearchVector = class extends MastraVector {
865
866
  } catch (error) {
866
867
  throw new MastraError(
867
868
  {
868
- id: "STORAGE_ELASTICSEARCH_VECTOR_UPDATE_BY_FILTER_FAILED",
869
+ id: createVectorErrorId("ELASTICSEARCH", "UPDATE_VECTOR_BY_FILTER", "FAILED"),
869
870
  domain: ErrorDomain.STORAGE,
870
871
  category: ErrorCategory.THIRD_PARTY,
871
872
  details: {
@@ -897,7 +898,7 @@ var ElasticSearchVector = class extends MastraVector {
897
898
  }
898
899
  throw new MastraError(
899
900
  {
900
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTOR_FAILED",
901
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_VECTOR", "FAILED"),
901
902
  domain: ErrorDomain.STORAGE,
902
903
  category: ErrorCategory.THIRD_PARTY,
903
904
  details: {
@@ -912,7 +913,7 @@ var ElasticSearchVector = class extends MastraVector {
912
913
  async deleteVectors({ indexName, filter, ids }) {
913
914
  if (ids && filter) {
914
915
  throw new MastraError({
915
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
916
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "MUTUALLY_EXCLUSIVE"),
916
917
  domain: ErrorDomain.STORAGE,
917
918
  category: ErrorCategory.USER,
918
919
  text: "ids and filter are mutually exclusive",
@@ -921,7 +922,7 @@ var ElasticSearchVector = class extends MastraVector {
921
922
  }
922
923
  if (!ids && !filter) {
923
924
  throw new MastraError({
924
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
925
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "NO_TARGET"),
925
926
  domain: ErrorDomain.STORAGE,
926
927
  category: ErrorCategory.USER,
927
928
  text: "Either filter or ids must be provided",
@@ -930,7 +931,7 @@ var ElasticSearchVector = class extends MastraVector {
930
931
  }
931
932
  if (ids && ids.length === 0) {
932
933
  throw new MastraError({
933
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
934
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "EMPTY_IDS"),
934
935
  domain: ErrorDomain.STORAGE,
935
936
  category: ErrorCategory.USER,
936
937
  text: "Cannot delete with empty ids array",
@@ -939,7 +940,7 @@ var ElasticSearchVector = class extends MastraVector {
939
940
  }
940
941
  if (filter && Object.keys(filter).length === 0) {
941
942
  throw new MastraError({
942
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS",
943
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "EMPTY_FILTER"),
943
944
  domain: ErrorDomain.STORAGE,
944
945
  category: ErrorCategory.USER,
945
946
  text: "Cannot delete with empty filter",
@@ -984,7 +985,7 @@ var ElasticSearchVector = class extends MastraVector {
984
985
  const failedItemDetails = failedItems.map((item) => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`).join("; ");
985
986
  const mastraError = new MastraError(
986
987
  {
987
- id: "STORAGE_ELASTICSEARCH_VECTOR_BULK_DELETE_PARTIAL_FAILURE",
988
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "BULK_PARTIAL_FAILURE"),
988
989
  text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,
989
990
  domain: ErrorDomain.STORAGE,
990
991
  category: ErrorCategory.THIRD_PARTY,
@@ -1017,7 +1018,7 @@ var ElasticSearchVector = class extends MastraVector {
1017
1018
  if (error instanceof MastraError) throw error;
1018
1019
  throw new MastraError(
1019
1020
  {
1020
- id: "STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_FAILED",
1021
+ id: createVectorErrorId("ELASTICSEARCH", "DELETE_VECTORS", "FAILED"),
1021
1022
  domain: ErrorDomain.STORAGE,
1022
1023
  category: ErrorCategory.THIRD_PARTY,
1023
1024
  details: {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["fieldWithKeyword","ElasticSearchClient"],"mappings":";;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4C,oBAAA,CAAgD;AAAA,EAC9E,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAG,oBAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAM,CAAA;AAAA,MAC/B,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,KAAA,EAAO,CAAC,QAAQ,CAAA;AAAA,MAChB,QAAQ;AAAC,KACX;AAAA,EACF;AAAA,EAEA,UAAU,MAAA,EAA+D;AACvE,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAO,MAAA;AACjC,IAAA,IAAA,CAAK,eAAe,MAAM,CAAA;AAC1B,IAAA,OAAO,IAAA,CAAK,cAAc,MAAM,CAAA;AAAA,EAClC;AAAA,EAEQ,cA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,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_CREATE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_LIST_INDEXES_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_FETCH_FAILED',\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_VALIDATE_INDEX_DIMENSION_MISMATCH',\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\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 const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_BULK_PARTIAL_FAILURE',\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPSERT_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_QUERY_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\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(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_NO_UPDATES',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_MISSING_PARAMS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_UPDATE_BY_FILTER_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\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({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_BULK_DELETE_PARTIAL_FAILURE',\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: 'STORAGE_ELASTICSEARCH_VECTOR_DELETE_VECTORS_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["fieldWithKeyword","ElasticSearchClient"],"mappings":";;;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4C,o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,SAAA;AAAA,UACP,KAAA,EAAQ,gBAAA,IAA4B,EAAE,SAAA,EAAW,EAAC,EAAE;AAAA,UACpD,OAAA,EAAS;AAAA,SACV,CAAA;AAAA,MACH;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,KAAA,YAAiB,aAAa,MAAM,KAAA;AACxC,MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,mBAAA,CAAoB,eAAA,EAAiB,gBAAA,EAAkB,QAAQ,CAAA;AAAA,UACnE,QAAQ,WAAA,CAAY,OAAA;AAAA,UACpB,UAAU,aAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { createVectorErrorId } from '@mastra/core/storage';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'INVALID_ARGS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'LIST_INDEXES', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'FETCH_FAILED'),\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'DIMENSION_MISMATCH'),\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\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 const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'QUERY', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\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(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_UPDATES'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR_BY_FILTER', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\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({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_IDS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/elasticsearch",
3
- "version": "1.0.0-beta.2",
3
+ "version": "1.0.0-beta.3",
4
4
  "description": "ElasticSearch vector store provider for Mastra",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -30,10 +30,10 @@
30
30
  "tsup": "^8.5.0",
31
31
  "typescript": "^5.8.3",
32
32
  "vitest": "4.0.12",
33
+ "@internal/types-builder": "0.0.28",
33
34
  "@internal/lint": "0.0.53",
34
35
  "@internal/storage-test-utils": "0.0.49",
35
- "@internal/types-builder": "0.0.28",
36
- "@mastra/core": "1.0.0-beta.6"
36
+ "@mastra/core": "1.0.0-beta.7"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@mastra/core": ">=1.0.0-0 <2.0.0-0"