@mastra/opensearch 0.0.0-tsconfig-compile-20250703214351 → 0.0.0-update-scorers-api-20250801170445

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,12 +1,55 @@
1
1
  # @mastra/opensearch
2
2
 
3
- ## 0.0.0-tsconfig-compile-20250703214351
3
+ ## 0.0.0-update-scorers-api-20250801170445
4
4
 
5
5
  ### Patch Changes
6
6
 
7
- - Updated dependencies [b790fd1]
8
- - Updated dependencies [f36e4f1]
9
- - @mastra/core@0.0.0-tsconfig-compile-20250703214351
7
+ - Updated dependencies [c6f12c7]
8
+ - @mastra/core@0.0.0-update-scorers-api-20250801170445
9
+
10
+ ## 0.11.2
11
+
12
+ ### Patch Changes
13
+
14
+ - f42c4c2: update peer deps for packages to latest core range
15
+ - Updated dependencies [510e2c8]
16
+ - Updated dependencies [2f72fb2]
17
+ - Updated dependencies [27cc97a]
18
+ - Updated dependencies [3f89307]
19
+ - Updated dependencies [9eda7d4]
20
+ - Updated dependencies [9d49408]
21
+ - Updated dependencies [41daa63]
22
+ - Updated dependencies [ad0a58b]
23
+ - Updated dependencies [254a36b]
24
+ - Updated dependencies [2ecf658]
25
+ - Updated dependencies [7a7754f]
26
+ - Updated dependencies [fc92d80]
27
+ - Updated dependencies [e0f73c6]
28
+ - Updated dependencies [0b89602]
29
+ - Updated dependencies [4d37822]
30
+ - Updated dependencies [23a6a7c]
31
+ - Updated dependencies [cda801d]
32
+ - Updated dependencies [a77c823]
33
+ - Updated dependencies [ff9c125]
34
+ - Updated dependencies [09bca64]
35
+ - Updated dependencies [b8efbb9]
36
+ - Updated dependencies [71466e7]
37
+ - Updated dependencies [0c99fbe]
38
+ - @mastra/core@0.12.0
39
+
40
+ ## 0.11.2-alpha.0
41
+
42
+ ### Patch Changes
43
+
44
+ - f42c4c2: update peer deps for packages to latest core range
45
+ - @mastra/core@0.12.0-alpha.5
46
+
47
+ ## 0.11.1
48
+
49
+ ### Patch Changes
50
+
51
+ - ce088f5: Update all peerdeps to latest core
52
+ - @mastra/core@0.11.1
10
53
 
11
54
  ## 0.11.0
12
55
 
package/LICENSE.md CHANGED
@@ -1,46 +1,15 @@
1
- # Elastic License 2.0 (ELv2)
1
+ # Apache License 2.0
2
2
 
3
- Copyright (c) 2025 Mastra AI, Inc.
3
+ Copyright (c) 2025 Kepler Software, Inc.
4
4
 
5
- **Acceptance**
6
- By using the software, you agree to all of the terms and conditions below.
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
7
8
 
8
- **Copyright License**
9
- The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
10
 
11
- **Limitations**
12
- You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
13
-
14
- You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
15
-
16
- You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
17
-
18
- **Patents**
19
- The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
20
-
21
- **Notices**
22
- You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
23
-
24
- If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
25
-
26
- **No Other Rights**
27
- These terms do not imply any licenses other than those expressly granted in these terms.
28
-
29
- **Termination**
30
- If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
31
-
32
- **No Liability**
33
- As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
34
-
35
- **Definitions**
36
- The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
37
-
38
- _you_ refers to the individual or entity agreeing to these terms.
39
-
40
- _your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
41
-
42
- _your licenses_ are all the licenses granted to you for the software under these terms.
43
-
44
- _use_ means anything you do with the software requiring one of your licenses.
45
-
46
- _trademark_ means trademarks, service marks, and similar rights.
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -721,3 +721,5 @@ var OpenSearchVector = class extends vector.MastraVector {
721
721
  };
722
722
 
723
723
  exports.OpenSearchVector = OpenSearchVector;
724
+ //# sourceMappingURL=index.cjs.map
725
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["BaseFilterTranslator","fieldWithKeyword","MastraVector","OpenSearchClient","MastraError","ErrorDomain","ErrorCategory","error"],"mappings":";;;;;;;;AA2BO,IAAM,0BAAA,GAAN,cAAyCA,2BAAA,CAA6C;AAAA,EACxE,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAGA,2BAAA,CAAqB,iBAAA;AAAA,MACxB,O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AAA,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 OpenSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype OpenSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype OpenSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type OpenSearchVectorFilter = VectorFilter<\n keyof OpenSearchOperatorValueMap,\n OpenSearchOperatorValueMap,\n OpenSearchLogicalOperatorValueMap,\n OpenSearchBlacklisted\n>;\n/**\n * Translator for OpenSearch filter queries.\n * Maintains OpenSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class OpenSearchFilterTranslator extends BaseFilterTranslator<OpenSearchVectorFilter> {\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?: OpenSearchVectorFilter): OpenSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: OpenSearchVectorFilter): 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 },\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 * Translates regex patterns to OpenSearch 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 // Check for problematic patterns (like newlines, etc.)\n if (regexValue.includes('\\n') || regexValue.includes('\\r')) {\n // For patterns with newlines, use a simpler approach\n // OpenSearch doesn't support dotall flag like JavaScript\n return { match: { [field]: value } };\n }\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 // Create wildcard pattern\n let wildcardPattern = processedRegex;\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 // Escape any backslashes to prevent OpenSearch from misinterpreting them\n const escapedRegex = regexValue.replace(/\\\\/g, '\\\\\\\\');\n return { regexp: { [field]: escapedRegex } };\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 OpenSearch 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 type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n} from '@mastra/core';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { MastraVector } from '@mastra/core/vector';\nimport { Client as OpenSearchClient } from '@opensearch-project/opensearch';\nimport { OpenSearchFilterTranslator } from './filter';\nimport type { OpenSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosinesimil',\n euclidean: 'l2',\n dotproduct: 'innerproduct',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosinesimil: 'cosine',\n l2: 'euclidean',\n innerproduct: 'dotproduct',\n} as const;\n\ntype OpenSearchVectorParams = QueryVectorParams<OpenSearchVectorFilter>;\n\nexport class OpenSearchVector extends MastraVector<OpenSearchVectorFilter> {\n private client: OpenSearchClient;\n\n /**\n * Creates a new OpenSearchVector client.\n *\n * @param {string} url - The url of the OpenSearch node.\n */\n constructor({ url }: { url: string }) {\n super();\n this.client = new OpenSearchClient({ 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_OPENSEARCH_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 body: {\n settings: { index: { knn: true } },\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'knn_vector',\n dimension: dimension,\n method: {\n name: 'hnsw',\n space_type: METRIC_MAPPING[metric],\n engine: 'faiss',\n parameters: { ef_construction: 128, m: 16 },\n },\n },\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_OPENSEARCH_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.body\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined) => index !== undefined);\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_VECTOR_LIST_INDEXES_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n const { body: indexInfo } = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const spaceType = embedding.method.space_type as keyof typeof REVERSE_METRIC_MAPPING;\n\n const { body: countInfo } = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dimension),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[spaceType],\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) {\n const mastraError = new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_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 }\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 await this.client.bulk({ body: operations, refresh: true });\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_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. For more on filters in OpenSearch, see the filtering reference: https://opensearch.org/docs/latest/query-dsl/\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 }: OpenSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n body: {\n query: {\n bool: {\n must: { knn: { embedding: { vector: queryVector, k: topK } } },\n filter: translatedFilter ? [translatedFilter] : [],\n },\n },\n _source: ['id', 'metadata', 'embedding'],\n },\n });\n\n const results = response.body.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_OPENSEARCH_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 OpenSearch DSL.\n *\n * @param {OpenSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: OpenSearchVectorFilter): any {\n const translator = new OpenSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates a vector by its ID with the provided vector and/or metadata.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to update.\n * @param update - An object containing the vector and/or metadata to update.\n * @param update.vector - An optional array of numbers representing the new vector.\n * @param update.metadata - An optional record containing the new metadata.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void> {\n let existingDoc;\n try {\n if (!update.vector && !update.metadata) {\n throw new Error('No updates provided');\n }\n\n // First get the current document to merge with updates\n const { body } = await this.client\n\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 (!body || !body._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = body;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, id },\n },\n error,\n );\n }\n\n const source = existingDoc._source;\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 console.log(`1`);\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n console.log(`2`);\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 console.log(`3`);\n await this.client.index({\n index: indexName,\n id: id,\n body: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, id },\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_OPENSEARCH_VECTOR_DELETE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, id },\n },\n error,\n );\n }\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
- export { OpenSearchVector } from './_tsup-dts-rollup.js';
1
+ export * from './vector';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC"}
package/dist/index.js CHANGED
@@ -719,3 +719,5 @@ var OpenSearchVector = class extends MastraVector {
719
719
  };
720
720
 
721
721
  export { OpenSearchVector };
722
+ //# sourceMappingURL=index.js.map
723
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["fieldWithKeyword","OpenSearchClient"],"mappings":";;;;;;AA2BO,IAAM,0BAAA,GAAN,cAAyC,oBAAA,CAA6C;AAAA,EACxE,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,EAAyD;AACjE,IAAA,IAAI,IAAA,CAAK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MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,gDAAA;AAAA,UACJ,QAAQ,WAAA,CAAY,OAAA;AAAA,UACpB,UAAU,aAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS,EAAE,SAAA,EAAW,EAAA;AAAG,SAC3B;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,YAAA,CAAa,EAAE,SAAA,EAAW,IAAG,EAAsC;AACvE,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,OAAO,MAAA,CAAO;AAAA,QACvB,KAAA,EAAO,SAAA;AAAA,QACP,EAAA;AAAA,QACA,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,SAAS,KAAA,EAAgB;AAEvB,MAAA,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,IAAY,gBAAgB,KAAA,IAAS,KAAA,CAAM,eAAe,GAAA,EAAK;AAC3F,QAAA;AAAA,MACF;AACA,MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,gDAAA;AAAA,UACJ,QAAQ,WAAA,CAAY,OAAA;AAAA,UACpB,UAAU,aAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS,EAAE,SAAA,EAAW,EAAA;AAAG,SAC3B;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 OpenSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype OpenSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype OpenSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type OpenSearchVectorFilter = VectorFilter<\n keyof OpenSearchOperatorValueMap,\n OpenSearchOperatorValueMap,\n OpenSearchLogicalOperatorValueMap,\n OpenSearchBlacklisted\n>;\n/**\n * Translator for OpenSearch filter queries.\n * Maintains OpenSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class OpenSearchFilterTranslator extends BaseFilterTranslator<OpenSearchVectorFilter> {\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?: OpenSearchVectorFilter): OpenSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: OpenSearchVectorFilter): 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 },\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 * Translates regex patterns to OpenSearch 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 // Check for problematic patterns (like newlines, etc.)\n if (regexValue.includes('\\n') || regexValue.includes('\\r')) {\n // For patterns with newlines, use a simpler approach\n // OpenSearch doesn't support dotall flag like JavaScript\n return { match: { [field]: value } };\n }\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 // Create wildcard pattern\n let wildcardPattern = processedRegex;\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 // Escape any backslashes to prevent OpenSearch from misinterpreting them\n const escapedRegex = regexValue.replace(/\\\\/g, '\\\\\\\\');\n return { regexp: { [field]: escapedRegex } };\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 OpenSearch 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 type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n} from '@mastra/core';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { MastraVector } from '@mastra/core/vector';\nimport { Client as OpenSearchClient } from '@opensearch-project/opensearch';\nimport { OpenSearchFilterTranslator } from './filter';\nimport type { OpenSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosinesimil',\n euclidean: 'l2',\n dotproduct: 'innerproduct',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosinesimil: 'cosine',\n l2: 'euclidean',\n innerproduct: 'dotproduct',\n} as const;\n\ntype OpenSearchVectorParams = QueryVectorParams<OpenSearchVectorFilter>;\n\nexport class OpenSearchVector extends MastraVector<OpenSearchVectorFilter> {\n private client: OpenSearchClient;\n\n /**\n * Creates a new OpenSearchVector client.\n *\n * @param {string} url - The url of the OpenSearch node.\n */\n constructor({ url }: { url: string }) {\n super();\n this.client = new OpenSearchClient({ 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_OPENSEARCH_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 body: {\n settings: { index: { knn: true } },\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'knn_vector',\n dimension: dimension,\n method: {\n name: 'hnsw',\n space_type: METRIC_MAPPING[metric],\n engine: 'faiss',\n parameters: { ef_construction: 128, m: 16 },\n },\n },\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_OPENSEARCH_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.body\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined) => index !== undefined);\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_VECTOR_LIST_INDEXES_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n const { body: indexInfo } = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const spaceType = embedding.method.space_type as keyof typeof REVERSE_METRIC_MAPPING;\n\n const { body: countInfo } = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dimension),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[spaceType],\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) {\n const mastraError = new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_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 }\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 await this.client.bulk({ body: operations, refresh: true });\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_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. For more on filters in OpenSearch, see the filtering reference: https://opensearch.org/docs/latest/query-dsl/\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 }: OpenSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n body: {\n query: {\n bool: {\n must: { knn: { embedding: { vector: queryVector, k: topK } } },\n filter: translatedFilter ? [translatedFilter] : [],\n },\n },\n _source: ['id', 'metadata', 'embedding'],\n },\n });\n\n const results = response.body.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_OPENSEARCH_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 OpenSearch DSL.\n *\n * @param {OpenSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: OpenSearchVectorFilter): any {\n const translator = new OpenSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates a vector by its ID with the provided vector and/or metadata.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to update.\n * @param update - An object containing the vector and/or metadata to update.\n * @param update.vector - An optional array of numbers representing the new vector.\n * @param update.metadata - An optional record containing the new metadata.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void> {\n let existingDoc;\n try {\n if (!update.vector && !update.metadata) {\n throw new Error('No updates provided');\n }\n\n // First get the current document to merge with updates\n const { body } = await this.client\n\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 (!body || !body._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = body;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, id },\n },\n error,\n );\n }\n\n const source = existingDoc._source;\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 console.log(`1`);\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n console.log(`2`);\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 console.log(`3`);\n await this.client.index({\n index: indexName,\n id: id,\n body: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_OPENSEARCH_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, id },\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_OPENSEARCH_VECTOR_DELETE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, id },\n },\n error,\n );\n }\n }\n}\n"]}
@@ -0,0 +1,47 @@
1
+ import type { BlacklistedRootOperators, LogicalOperatorValueMap, OperatorSupport, OperatorValueMap, VectorFilter } from '@mastra/core/vector/filter';
2
+ import { BaseFilterTranslator } from '@mastra/core/vector/filter';
3
+ type OpenSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;
4
+ type OpenSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;
5
+ type OpenSearchBlacklisted = BlacklistedRootOperators | '$nor';
6
+ export type OpenSearchVectorFilter = VectorFilter<keyof OpenSearchOperatorValueMap, OpenSearchOperatorValueMap, OpenSearchLogicalOperatorValueMap, OpenSearchBlacklisted>;
7
+ /**
8
+ * Translator for OpenSearch filter queries.
9
+ * Maintains OpenSearch-compatible syntax while ensuring proper validation
10
+ * and normalization of values.
11
+ */
12
+ export declare class OpenSearchFilterTranslator extends BaseFilterTranslator<OpenSearchVectorFilter> {
13
+ protected getSupportedOperators(): OperatorSupport;
14
+ translate(filter?: OpenSearchVectorFilter): OpenSearchVectorFilter;
15
+ private translateNode;
16
+ /**
17
+ * Handles translation of nested objects with dot notation fields
18
+ */
19
+ private translateNestedObject;
20
+ private translateLogicalOperator;
21
+ private translateFieldOperator;
22
+ /**
23
+ * Translates regex patterns to OpenSearch query syntax
24
+ */
25
+ private translateRegexOperator;
26
+ private addKeywordIfNeeded;
27
+ /**
28
+ * Helper method to handle special cases for the $not operator
29
+ */
30
+ private handleNotOperatorSpecialCases;
31
+ private translateOperator;
32
+ /**
33
+ * Translates field conditions to OpenSearch query syntax
34
+ * Handles special cases like range queries and multiple operators
35
+ */
36
+ private translateFieldConditions;
37
+ /**
38
+ * Checks if conditions can be optimized to a range query
39
+ */
40
+ private canOptimizeToRangeQuery;
41
+ /**
42
+ * Creates a range query from numeric operators
43
+ */
44
+ private createRangeQuery;
45
+ }
46
+ export {};
47
+ //# sourceMappingURL=filter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter.d.ts","sourceRoot":"","sources":["../../src/vector/filter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,uBAAuB,EACvB,eAAe,EACf,gBAAgB,EAEhB,YAAY,EACb,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,KAAK,0BAA0B,GAAG,IAAI,CAAC,gBAAgB,EAAE,UAAU,GAAG,MAAM,GAAG,YAAY,CAAC,CAAC;AAE7F,KAAK,iCAAiC,GAAG,IAAI,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;AAE/E,KAAK,qBAAqB,GAAG,wBAAwB,GAAG,MAAM,CAAC;AAE/D,MAAM,MAAM,sBAAsB,GAAG,YAAY,CAC/C,MAAM,0BAA0B,EAChC,0BAA0B,EAC1B,iCAAiC,EACjC,qBAAqB,CACtB,CAAC;AACF;;;;GAIG;AACH,qBAAa,0BAA2B,SAAQ,oBAAoB,CAAC,sBAAsB,CAAC;cACvE,qBAAqB,IAAI,eAAe;IAU3D,SAAS,CAAC,MAAM,CAAC,EAAE,sBAAsB,GAAG,sBAAsB;IAMlE,OAAO,CAAC,aAAa;IAqFrB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IA4B7B,OAAO,CAAC,wBAAwB;IAsChC,OAAO,CAAC,sBAAsB;IAoF9B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IA4C9B,OAAO,CAAC,kBAAkB;IAY1B;;OAEG;IACH,OAAO,CAAC,6BAA6B;IAyBrC,OAAO,CAAC,iBAAiB;IAyDzB;;;OAGG;IACH,OAAO,CAAC,wBAAwB;IA+BhC;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAI/B;;OAEG;IACH,OAAO,CAAC,gBAAgB;CAOzB"}
@@ -0,0 +1,101 @@
1
+ import type { CreateIndexParams, DeleteIndexParams, DeleteVectorParams, DescribeIndexParams, IndexStats, QueryResult, QueryVectorParams, UpdateVectorParams, UpsertVectorParams } from '@mastra/core';
2
+ import { MastraVector } from '@mastra/core/vector';
3
+ import type { OpenSearchVectorFilter } from './filter';
4
+ type OpenSearchVectorParams = QueryVectorParams<OpenSearchVectorFilter>;
5
+ export declare class OpenSearchVector extends MastraVector<OpenSearchVectorFilter> {
6
+ private client;
7
+ /**
8
+ * Creates a new OpenSearchVector client.
9
+ *
10
+ * @param {string} url - The url of the OpenSearch node.
11
+ */
12
+ constructor({ url }: {
13
+ url: string;
14
+ });
15
+ /**
16
+ * Creates a new collection with the specified configuration.
17
+ *
18
+ * @param {string} indexName - The name of the collection to create.
19
+ * @param {number} dimension - The dimension of the vectors to be stored in the collection.
20
+ * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.
21
+ * @returns {Promise<void>} A promise that resolves when the collection is created.
22
+ */
23
+ createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
24
+ /**
25
+ * Lists all indexes.
26
+ *
27
+ * @returns {Promise<string[]>} A promise that resolves to an array of indexes.
28
+ */
29
+ listIndexes(): Promise<string[]>;
30
+ /**
31
+ * Retrieves statistics about a vector index.
32
+ *
33
+ * @param {string} indexName - The name of the index to describe
34
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
35
+ */
36
+ describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats>;
37
+ /**
38
+ * Deletes the specified index.
39
+ *
40
+ * @param {string} indexName - The name of the index to delete.
41
+ * @returns {Promise<void>} A promise that resolves when the index is deleted.
42
+ */
43
+ deleteIndex({ indexName }: DeleteIndexParams): Promise<void>;
44
+ /**
45
+ * Inserts or updates vectors in the specified collection.
46
+ *
47
+ * @param {string} indexName - The name of the collection to upsert into.
48
+ * @param {number[][]} vectors - An array of vectors to upsert.
49
+ * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.
50
+ * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.
51
+ * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.
52
+ */
53
+ upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
54
+ /**
55
+ * Queries the specified collection using a vector and optional filter.
56
+ *
57
+ * @param {string} indexName - The name of the collection to query.
58
+ * @param {number[]} queryVector - The vector to query with.
59
+ * @param {number} [topK] - The maximum number of results to return.
60
+ * @param {Record<string, any>} [filter] - An optional filter to apply to the query. For more on filters in OpenSearch, see the filtering reference: https://opensearch.org/docs/latest/query-dsl/
61
+ * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.
62
+ * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.
63
+ */
64
+ query({ indexName, queryVector, filter, topK, includeVector, }: OpenSearchVectorParams): Promise<QueryResult[]>;
65
+ /**
66
+ * Validates the dimensions of the vectors.
67
+ *
68
+ * @param {number[][]} vectors - The vectors to validate.
69
+ * @param {number} dimension - The dimension of the vectors.
70
+ * @returns {void}
71
+ */
72
+ private validateVectorDimensions;
73
+ /**
74
+ * Transforms the filter to the OpenSearch DSL.
75
+ *
76
+ * @param {OpenSearchVectorFilter} filter - The filter to transform.
77
+ * @returns {Record<string, any>} The transformed filter.
78
+ */
79
+ private transformFilter;
80
+ /**
81
+ * Updates a vector by its ID with the provided vector and/or metadata.
82
+ * @param indexName - The name of the index containing the vector.
83
+ * @param id - The ID of the vector to update.
84
+ * @param update - An object containing the vector and/or metadata to update.
85
+ * @param update.vector - An optional array of numbers representing the new vector.
86
+ * @param update.metadata - An optional record containing the new metadata.
87
+ * @returns A promise that resolves when the update is complete.
88
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
89
+ */
90
+ updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void>;
91
+ /**
92
+ * Deletes a vector by its ID.
93
+ * @param indexName - The name of the index containing the vector.
94
+ * @param id - The ID of the vector to delete.
95
+ * @returns A promise that resolves when the deletion is complete.
96
+ * @throws Will throw an error if the deletion operation fails.
97
+ */
98
+ deleteVector({ indexName, id }: DeleteVectorParams): Promise<void>;
99
+ }
100
+ export {};
101
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vector/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,EACnB,UAAU,EACV,WAAW,EACX,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGnD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAcvD,KAAK,sBAAsB,GAAG,iBAAiB,CAAC,sBAAsB,CAAC,CAAC;AAExE,qBAAa,gBAAiB,SAAQ,YAAY,CAAC,sBAAsB,CAAC;IACxE,OAAO,CAAC,MAAM,CAAmB;IAEjC;;;;OAIG;gBACS,EAAE,GAAG,EAAE,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE;IAKpC;;;;;;;OAOG;IACG,WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,MAAiB,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAqDhG;;;;OAIG;IACG,WAAW,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAoBtC;;;;;OAKG;IACG,aAAa,CAAC,EAAE,SAAS,EAAE,EAAE,mBAAmB,GAAG,OAAO,CAAC,UAAU,CAAC;IAe5E;;;;;OAKG;IACG,WAAW,CAAC,EAAE,SAAS,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBlE;;;;;;;;OAQG;IACG,MAAM,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,QAAa,EAAE,GAAG,EAAE,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IA+C/F;;;;;;;;;OASG;IACG,KAAK,CAAC,EACV,SAAS,EACT,WAAW,EACX,MAAM,EACN,IAAS,EACT,aAAqB,GACtB,EAAE,sBAAsB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAyClD;;;;;;OAMG;IACH,OAAO,CAAC,wBAAwB;IAMhC;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAKvB;;;;;;;;;OASG;IACG,YAAY,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAmFhF;;;;;;OAMG;IACG,YAAY,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;CAuBzE"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Vector store prompt for OpenSearch. This prompt details supported filter operators, syntax, and usage examples.
3
+ * Use this as a guide for constructing valid filters for OpenSearch vector queries in Mastra.
4
+ */
5
+ export declare const OPENSEARCH_PROMPT = "When querying OpenSearch, you can ONLY use the operators listed below. Any other operators will be rejected.\nImportant: Do not explain how to construct the filter\u2014use the specified operators and fields to search the content and return relevant results.\nIf a user tries to use an unsupported operator, reject the filter entirely and let them know that the operator is not supported.\n\nBasic Comparison Operators:\n- $eq: Exact match (default for field: value)\n Example: { \"category\": \"electronics\" }\n- $ne: Not equal\n Example: { \"category\": { \"$ne\": \"electronics\" } }\n- $gt: Greater than\n Example: { \"price\": { \"$gt\": 100 } }\n- $gte: Greater than or equal\n Example: { \"price\": { \"$gte\": 100 } }\n- $lt: Less than\n Example: { \"price\": { \"$lt\": 100 } }\n- $lte: Less than or equal\n Example: { \"price\": { \"$lte\": 100 } }\n\nArray Operators:\n- $in: Match any value in array\n Example: { \"category\": { \"$in\": [\"electronics\", \"books\"] } }\n- $nin: Does not match any value in array\n Example: { \"category\": { \"$nin\": [\"electronics\", \"books\"] } }\n- $all: Match all values in array\n Example: { \"tags\": { \"$all\": [\"premium\", \"sale\"] } }\n\nLogical Operators:\n- $and: Logical AND (implicit when using multiple conditions)\n Example: { \"$and\": [{ \"price\": { \"$gt\": 100 } }, { \"category\": \"electronics\" }] }\n- $or: Logical OR\n Example: { \"$or\": [{ \"price\": { \"$lt\": 50 } }, { \"category\": \"books\" }] }\n- $not: Logical NOT\n Example: { \"$not\": { \"category\": \"electronics\" } }\n\nElement Operators:\n- $exists: Check if field exists\n Example: { \"rating\": { \"$exists\": true } }\n\nRegex Operator:\n- $regex: Match using a regular expression (ECMAScript syntax)\n Example: { \"name\": { \"$regex\": \"^Sam.*son$\" } }\n Note: Regex queries are supported for string fields only. Use valid ECMAScript patterns; invalid patterns will throw an error.\n\nRestrictions:\n- Nested fields are supported using dot notation (e.g., \"address.city\").\n- Multiple conditions on the same field are supported (e.g., { \"price\": { \"$gte\": 100, \"$lte\": 1000 } }).\n- Only logical operators ($and, $or, $not) can be used at the top level.\n- All other operators must be used within a field condition.\n Valid: { \"field\": { \"$gt\": 100 } }\n Valid: { \"$and\": [...] }\n Invalid: { \"$gt\": 100 }\n- Logical operators must contain field conditions, not direct operators.\n Valid: { \"$and\": [{ \"field\": { \"$gt\": 100 } }] }\n Invalid: { \"$and\": [{ \"$gt\": 100 }] }\n- $not operator:\n - Must be an object\n - Cannot be empty\n - Can be used at field level or top level\n - Valid: { \"$not\": { \"field\": \"value\" } }\n - Valid: { \"field\": { \"$not\": { \"$eq\": \"value\" } } }\n- Array operators work on array fields only.\n- Empty arrays in conditions are handled gracefully.\n- Regex queries are case-sensitive by default; use patterns accordingly.\n\nExample Complex Query:\n{\n \"$and\": [\n { \"category\": { \"$in\": [\"electronics\", \"computers\"] } },\n { \"price\": { \"$gte\": 100, \"$lte\": 1000 } },\n { \"tags\": { \"$all\": [\"premium\"] } },\n { \"rating\": { \"$exists\": true, \"$gt\": 4 } },\n { \"$or\": [\n { \"stock\": { \"$gt\": 0 } },\n { \"preorder\": true }\n ]},\n { \"name\": { \"$regex\": \"^Sam.*son$\" } }\n ]\n}";
6
+ //# sourceMappingURL=prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/vector/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,iBAAiB,m0GA6E5B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/opensearch",
3
- "version": "0.0.0-tsconfig-compile-20250703214351",
3
+ "version": "0.0.0-update-scorers-api-20250801170445",
4
4
  "description": "OpenSearch vector store provider for Mastra",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -24,19 +24,19 @@
24
24
  "devDependencies": {
25
25
  "@microsoft/api-extractor": "^7.52.8",
26
26
  "@types/node": "^20.19.0",
27
- "eslint": "^9.29.0",
27
+ "eslint": "^9.30.1",
28
28
  "tsup": "^8.5.0",
29
29
  "typescript": "^5.8.3",
30
30
  "vitest": "^3.2.4",
31
- "@internal/lint": "0.0.0-tsconfig-compile-20250703214351",
32
- "@mastra/core": "0.0.0-tsconfig-compile-20250703214351"
31
+ "@internal/lint": "0.0.0-update-scorers-api-20250801170445",
32
+ "@mastra/core": "0.0.0-update-scorers-api-20250801170445"
33
33
  },
34
34
  "peerDependencies": {
35
- "@mastra/core": "0.0.0-tsconfig-compile-20250703214351"
35
+ "@mastra/core": "0.0.0-update-scorers-api-20250801170445"
36
36
  },
37
37
  "scripts": {
38
- "build": "tsup src/index.ts --format esm,cjs --experimental-dts --clean --treeshake=smallest --splitting",
39
- "build:watch": "pnpm build --watch",
38
+ "build": "tsup --silent --config tsup.config.ts",
39
+ "build:watch": "tsup --watch --silent --config tsup.config.ts",
40
40
  "pretest": "docker compose up -d && (for i in $(seq 1 30); do curl -s http://localhost:9200/_cluster/health | grep -q '\"status\"' && break || (sleep 1; [ $i -eq 30 ] && exit 1); done)",
41
41
  "test": "vitest run",
42
42
  "posttest": "docker compose down -v",
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": ["./tsconfig.json", "../../tsconfig.build.json"],
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src"
6
+ },
7
+ "include": ["src/**/*"],
8
+ "exclude": ["node_modules", "**/*.test.ts", "src/**/*.mock.ts"]
9
+ }
package/tsconfig.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "extends": "../../tsconfig.node.json",
3
- "include": ["src/**/*"],
3
+ "include": ["src/**/*", "tsup.config.ts"],
4
4
  "exclude": ["node_modules", "**/*.test.ts"]
5
5
  }
package/tsup.config.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { spawn } from 'child_process';
2
+ import { promisify } from 'util';
3
+ import { defineConfig } from 'tsup';
4
+
5
+ const exec = promisify(spawn);
6
+
7
+ export default defineConfig({
8
+ entry: ['src/index.ts'],
9
+ format: ['esm', 'cjs'],
10
+ clean: true,
11
+ dts: false,
12
+ splitting: true,
13
+ treeshake: {
14
+ preset: 'smallest',
15
+ },
16
+ sourcemap: true,
17
+ onSuccess: async () => {
18
+ await exec('pnpm', ['tsc', '-p', 'tsconfig.build.json'], {
19
+ stdio: 'inherit',
20
+ });
21
+ },
22
+ });
@@ -1,172 +0,0 @@
1
- import { BaseFilterTranslator } from '@mastra/core/vector/filter';
2
- import type { BlacklistedRootOperators } from '@mastra/core/vector/filter';
3
- import type { CreateIndexParams } from '@mastra/core';
4
- import type { DeleteIndexParams } from '@mastra/core';
5
- import type { DeleteVectorParams } from '@mastra/core';
6
- import type { DescribeIndexParams } from '@mastra/core';
7
- import type { IndexStats } from '@mastra/core';
8
- import type { LogicalOperatorValueMap } from '@mastra/core/vector/filter';
9
- import { MastraVector } from '@mastra/core/vector';
10
- import type { OperatorSupport } from '@mastra/core/vector/filter';
11
- import type { OperatorValueMap } from '@mastra/core/vector/filter';
12
- import type { QueryResult } from '@mastra/core';
13
- import type { QueryVectorParams } from '@mastra/core';
14
- import type { UpdateVectorParams } from '@mastra/core';
15
- import type { UpsertVectorParams } from '@mastra/core';
16
- import type { VectorFilter } from '@mastra/core/vector/filter';
17
-
18
- /**
19
- * Vector store prompt for OpenSearch. This prompt details supported filter operators, syntax, and usage examples.
20
- * Use this as a guide for constructing valid filters for OpenSearch vector queries in Mastra.
21
- */
22
- export declare const OPENSEARCH_PROMPT = "When querying OpenSearch, you can ONLY use the operators listed below. Any other operators will be rejected.\nImportant: Do not explain how to construct the filter\u2014use the specified operators and fields to search the content and return relevant results.\nIf a user tries to use an unsupported operator, reject the filter entirely and let them know that the operator is not supported.\n\nBasic Comparison Operators:\n- $eq: Exact match (default for field: value)\n Example: { \"category\": \"electronics\" }\n- $ne: Not equal\n Example: { \"category\": { \"$ne\": \"electronics\" } }\n- $gt: Greater than\n Example: { \"price\": { \"$gt\": 100 } }\n- $gte: Greater than or equal\n Example: { \"price\": { \"$gte\": 100 } }\n- $lt: Less than\n Example: { \"price\": { \"$lt\": 100 } }\n- $lte: Less than or equal\n Example: { \"price\": { \"$lte\": 100 } }\n\nArray Operators:\n- $in: Match any value in array\n Example: { \"category\": { \"$in\": [\"electronics\", \"books\"] } }\n- $nin: Does not match any value in array\n Example: { \"category\": { \"$nin\": [\"electronics\", \"books\"] } }\n- $all: Match all values in array\n Example: { \"tags\": { \"$all\": [\"premium\", \"sale\"] } }\n\nLogical Operators:\n- $and: Logical AND (implicit when using multiple conditions)\n Example: { \"$and\": [{ \"price\": { \"$gt\": 100 } }, { \"category\": \"electronics\" }] }\n- $or: Logical OR\n Example: { \"$or\": [{ \"price\": { \"$lt\": 50 } }, { \"category\": \"books\" }] }\n- $not: Logical NOT\n Example: { \"$not\": { \"category\": \"electronics\" } }\n\nElement Operators:\n- $exists: Check if field exists\n Example: { \"rating\": { \"$exists\": true } }\n\nRegex Operator:\n- $regex: Match using a regular expression (ECMAScript syntax)\n Example: { \"name\": { \"$regex\": \"^Sam.*son$\" } }\n Note: Regex queries are supported for string fields only. Use valid ECMAScript patterns; invalid patterns will throw an error.\n\nRestrictions:\n- Nested fields are supported using dot notation (e.g., \"address.city\").\n- Multiple conditions on the same field are supported (e.g., { \"price\": { \"$gte\": 100, \"$lte\": 1000 } }).\n- Only logical operators ($and, $or, $not) can be used at the top level.\n- All other operators must be used within a field condition.\n Valid: { \"field\": { \"$gt\": 100 } }\n Valid: { \"$and\": [...] }\n Invalid: { \"$gt\": 100 }\n- Logical operators must contain field conditions, not direct operators.\n Valid: { \"$and\": [{ \"field\": { \"$gt\": 100 } }] }\n Invalid: { \"$and\": [{ \"$gt\": 100 }] }\n- $not operator:\n - Must be an object\n - Cannot be empty\n - Can be used at field level or top level\n - Valid: { \"$not\": { \"field\": \"value\" } }\n - Valid: { \"field\": { \"$not\": { \"$eq\": \"value\" } } }\n- Array operators work on array fields only.\n- Empty arrays in conditions are handled gracefully.\n- Regex queries are case-sensitive by default; use patterns accordingly.\n\nExample Complex Query:\n{\n \"$and\": [\n { \"category\": { \"$in\": [\"electronics\", \"computers\"] } },\n { \"price\": { \"$gte\": 100, \"$lte\": 1000 } },\n { \"tags\": { \"$all\": [\"premium\"] } },\n { \"rating\": { \"$exists\": true, \"$gt\": 4 } },\n { \"$or\": [\n { \"stock\": { \"$gt\": 0 } },\n { \"preorder\": true }\n ]},\n { \"name\": { \"$regex\": \"^Sam.*son$\" } }\n ]\n}";
23
-
24
- declare type OpenSearchBlacklisted = BlacklistedRootOperators | '$nor';
25
-
26
- /**
27
- * Translator for OpenSearch filter queries.
28
- * Maintains OpenSearch-compatible syntax while ensuring proper validation
29
- * and normalization of values.
30
- */
31
- export declare class OpenSearchFilterTranslator extends BaseFilterTranslator<OpenSearchVectorFilter> {
32
- protected getSupportedOperators(): OperatorSupport;
33
- translate(filter?: OpenSearchVectorFilter): OpenSearchVectorFilter;
34
- private translateNode;
35
- /**
36
- * Handles translation of nested objects with dot notation fields
37
- */
38
- private translateNestedObject;
39
- private translateLogicalOperator;
40
- private translateFieldOperator;
41
- /**
42
- * Translates regex patterns to OpenSearch query syntax
43
- */
44
- private translateRegexOperator;
45
- private addKeywordIfNeeded;
46
- /**
47
- * Helper method to handle special cases for the $not operator
48
- */
49
- private handleNotOperatorSpecialCases;
50
- private translateOperator;
51
- /**
52
- * Translates field conditions to OpenSearch query syntax
53
- * Handles special cases like range queries and multiple operators
54
- */
55
- private translateFieldConditions;
56
- /**
57
- * Checks if conditions can be optimized to a range query
58
- */
59
- private canOptimizeToRangeQuery;
60
- /**
61
- * Creates a range query from numeric operators
62
- */
63
- private createRangeQuery;
64
- }
65
-
66
- declare type OpenSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;
67
-
68
- declare type OpenSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;
69
-
70
- declare class OpenSearchVector extends MastraVector<OpenSearchVectorFilter> {
71
- private client;
72
- /**
73
- * Creates a new OpenSearchVector client.
74
- *
75
- * @param {string} url - The url of the OpenSearch node.
76
- */
77
- constructor({ url }: {
78
- url: string;
79
- });
80
- /**
81
- * Creates a new collection with the specified configuration.
82
- *
83
- * @param {string} indexName - The name of the collection to create.
84
- * @param {number} dimension - The dimension of the vectors to be stored in the collection.
85
- * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.
86
- * @returns {Promise<void>} A promise that resolves when the collection is created.
87
- */
88
- createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
89
- /**
90
- * Lists all indexes.
91
- *
92
- * @returns {Promise<string[]>} A promise that resolves to an array of indexes.
93
- */
94
- listIndexes(): Promise<string[]>;
95
- /**
96
- * Retrieves statistics about a vector index.
97
- *
98
- * @param {string} indexName - The name of the index to describe
99
- * @returns A promise that resolves to the index statistics including dimension, count and metric
100
- */
101
- describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats>;
102
- /**
103
- * Deletes the specified index.
104
- *
105
- * @param {string} indexName - The name of the index to delete.
106
- * @returns {Promise<void>} A promise that resolves when the index is deleted.
107
- */
108
- deleteIndex({ indexName }: DeleteIndexParams): Promise<void>;
109
- /**
110
- * Inserts or updates vectors in the specified collection.
111
- *
112
- * @param {string} indexName - The name of the collection to upsert into.
113
- * @param {number[][]} vectors - An array of vectors to upsert.
114
- * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.
115
- * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.
116
- * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.
117
- */
118
- upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
119
- /**
120
- * Queries the specified collection using a vector and optional filter.
121
- *
122
- * @param {string} indexName - The name of the collection to query.
123
- * @param {number[]} queryVector - The vector to query with.
124
- * @param {number} [topK] - The maximum number of results to return.
125
- * @param {Record<string, any>} [filter] - An optional filter to apply to the query. For more on filters in OpenSearch, see the filtering reference: https://opensearch.org/docs/latest/query-dsl/
126
- * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.
127
- * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.
128
- */
129
- query({ indexName, queryVector, filter, topK, includeVector, }: OpenSearchVectorParams): Promise<QueryResult[]>;
130
- /**
131
- * Validates the dimensions of the vectors.
132
- *
133
- * @param {number[][]} vectors - The vectors to validate.
134
- * @param {number} dimension - The dimension of the vectors.
135
- * @returns {void}
136
- */
137
- private validateVectorDimensions;
138
- /**
139
- * Transforms the filter to the OpenSearch DSL.
140
- *
141
- * @param {OpenSearchVectorFilter} filter - The filter to transform.
142
- * @returns {Record<string, any>} The transformed filter.
143
- */
144
- private transformFilter;
145
- /**
146
- * Updates a vector by its ID with the provided vector and/or metadata.
147
- * @param indexName - The name of the index containing the vector.
148
- * @param id - The ID of the vector to update.
149
- * @param update - An object containing the vector and/or metadata to update.
150
- * @param update.vector - An optional array of numbers representing the new vector.
151
- * @param update.metadata - An optional record containing the new metadata.
152
- * @returns A promise that resolves when the update is complete.
153
- * @throws Will throw an error if no updates are provided or if the update operation fails.
154
- */
155
- updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void>;
156
- /**
157
- * Deletes a vector by its ID.
158
- * @param indexName - The name of the index containing the vector.
159
- * @param id - The ID of the vector to delete.
160
- * @returns A promise that resolves when the deletion is complete.
161
- * @throws Will throw an error if the deletion operation fails.
162
- */
163
- deleteVector({ indexName, id }: DeleteVectorParams): Promise<void>;
164
- }
165
- export { OpenSearchVector }
166
- export { OpenSearchVector as OpenSearchVector_alias_1 }
167
-
168
- export declare type OpenSearchVectorFilter = VectorFilter<keyof OpenSearchOperatorValueMap, OpenSearchOperatorValueMap, OpenSearchLogicalOperatorValueMap, OpenSearchBlacklisted>;
169
-
170
- declare type OpenSearchVectorParams = QueryVectorParams<OpenSearchVectorFilter>;
171
-
172
- export { }
@@ -1,172 +0,0 @@
1
- import { BaseFilterTranslator } from '@mastra/core/vector/filter';
2
- import type { BlacklistedRootOperators } from '@mastra/core/vector/filter';
3
- import type { CreateIndexParams } from '@mastra/core';
4
- import type { DeleteIndexParams } from '@mastra/core';
5
- import type { DeleteVectorParams } from '@mastra/core';
6
- import type { DescribeIndexParams } from '@mastra/core';
7
- import type { IndexStats } from '@mastra/core';
8
- import type { LogicalOperatorValueMap } from '@mastra/core/vector/filter';
9
- import { MastraVector } from '@mastra/core/vector';
10
- import type { OperatorSupport } from '@mastra/core/vector/filter';
11
- import type { OperatorValueMap } from '@mastra/core/vector/filter';
12
- import type { QueryResult } from '@mastra/core';
13
- import type { QueryVectorParams } from '@mastra/core';
14
- import type { UpdateVectorParams } from '@mastra/core';
15
- import type { UpsertVectorParams } from '@mastra/core';
16
- import type { VectorFilter } from '@mastra/core/vector/filter';
17
-
18
- /**
19
- * Vector store prompt for OpenSearch. This prompt details supported filter operators, syntax, and usage examples.
20
- * Use this as a guide for constructing valid filters for OpenSearch vector queries in Mastra.
21
- */
22
- export declare const OPENSEARCH_PROMPT = "When querying OpenSearch, you can ONLY use the operators listed below. Any other operators will be rejected.\nImportant: Do not explain how to construct the filter\u2014use the specified operators and fields to search the content and return relevant results.\nIf a user tries to use an unsupported operator, reject the filter entirely and let them know that the operator is not supported.\n\nBasic Comparison Operators:\n- $eq: Exact match (default for field: value)\n Example: { \"category\": \"electronics\" }\n- $ne: Not equal\n Example: { \"category\": { \"$ne\": \"electronics\" } }\n- $gt: Greater than\n Example: { \"price\": { \"$gt\": 100 } }\n- $gte: Greater than or equal\n Example: { \"price\": { \"$gte\": 100 } }\n- $lt: Less than\n Example: { \"price\": { \"$lt\": 100 } }\n- $lte: Less than or equal\n Example: { \"price\": { \"$lte\": 100 } }\n\nArray Operators:\n- $in: Match any value in array\n Example: { \"category\": { \"$in\": [\"electronics\", \"books\"] } }\n- $nin: Does not match any value in array\n Example: { \"category\": { \"$nin\": [\"electronics\", \"books\"] } }\n- $all: Match all values in array\n Example: { \"tags\": { \"$all\": [\"premium\", \"sale\"] } }\n\nLogical Operators:\n- $and: Logical AND (implicit when using multiple conditions)\n Example: { \"$and\": [{ \"price\": { \"$gt\": 100 } }, { \"category\": \"electronics\" }] }\n- $or: Logical OR\n Example: { \"$or\": [{ \"price\": { \"$lt\": 50 } }, { \"category\": \"books\" }] }\n- $not: Logical NOT\n Example: { \"$not\": { \"category\": \"electronics\" } }\n\nElement Operators:\n- $exists: Check if field exists\n Example: { \"rating\": { \"$exists\": true } }\n\nRegex Operator:\n- $regex: Match using a regular expression (ECMAScript syntax)\n Example: { \"name\": { \"$regex\": \"^Sam.*son$\" } }\n Note: Regex queries are supported for string fields only. Use valid ECMAScript patterns; invalid patterns will throw an error.\n\nRestrictions:\n- Nested fields are supported using dot notation (e.g., \"address.city\").\n- Multiple conditions on the same field are supported (e.g., { \"price\": { \"$gte\": 100, \"$lte\": 1000 } }).\n- Only logical operators ($and, $or, $not) can be used at the top level.\n- All other operators must be used within a field condition.\n Valid: { \"field\": { \"$gt\": 100 } }\n Valid: { \"$and\": [...] }\n Invalid: { \"$gt\": 100 }\n- Logical operators must contain field conditions, not direct operators.\n Valid: { \"$and\": [{ \"field\": { \"$gt\": 100 } }] }\n Invalid: { \"$and\": [{ \"$gt\": 100 }] }\n- $not operator:\n - Must be an object\n - Cannot be empty\n - Can be used at field level or top level\n - Valid: { \"$not\": { \"field\": \"value\" } }\n - Valid: { \"field\": { \"$not\": { \"$eq\": \"value\" } } }\n- Array operators work on array fields only.\n- Empty arrays in conditions are handled gracefully.\n- Regex queries are case-sensitive by default; use patterns accordingly.\n\nExample Complex Query:\n{\n \"$and\": [\n { \"category\": { \"$in\": [\"electronics\", \"computers\"] } },\n { \"price\": { \"$gte\": 100, \"$lte\": 1000 } },\n { \"tags\": { \"$all\": [\"premium\"] } },\n { \"rating\": { \"$exists\": true, \"$gt\": 4 } },\n { \"$or\": [\n { \"stock\": { \"$gt\": 0 } },\n { \"preorder\": true }\n ]},\n { \"name\": { \"$regex\": \"^Sam.*son$\" } }\n ]\n}";
23
-
24
- declare type OpenSearchBlacklisted = BlacklistedRootOperators | '$nor';
25
-
26
- /**
27
- * Translator for OpenSearch filter queries.
28
- * Maintains OpenSearch-compatible syntax while ensuring proper validation
29
- * and normalization of values.
30
- */
31
- export declare class OpenSearchFilterTranslator extends BaseFilterTranslator<OpenSearchVectorFilter> {
32
- protected getSupportedOperators(): OperatorSupport;
33
- translate(filter?: OpenSearchVectorFilter): OpenSearchVectorFilter;
34
- private translateNode;
35
- /**
36
- * Handles translation of nested objects with dot notation fields
37
- */
38
- private translateNestedObject;
39
- private translateLogicalOperator;
40
- private translateFieldOperator;
41
- /**
42
- * Translates regex patterns to OpenSearch query syntax
43
- */
44
- private translateRegexOperator;
45
- private addKeywordIfNeeded;
46
- /**
47
- * Helper method to handle special cases for the $not operator
48
- */
49
- private handleNotOperatorSpecialCases;
50
- private translateOperator;
51
- /**
52
- * Translates field conditions to OpenSearch query syntax
53
- * Handles special cases like range queries and multiple operators
54
- */
55
- private translateFieldConditions;
56
- /**
57
- * Checks if conditions can be optimized to a range query
58
- */
59
- private canOptimizeToRangeQuery;
60
- /**
61
- * Creates a range query from numeric operators
62
- */
63
- private createRangeQuery;
64
- }
65
-
66
- declare type OpenSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;
67
-
68
- declare type OpenSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;
69
-
70
- declare class OpenSearchVector extends MastraVector<OpenSearchVectorFilter> {
71
- private client;
72
- /**
73
- * Creates a new OpenSearchVector client.
74
- *
75
- * @param {string} url - The url of the OpenSearch node.
76
- */
77
- constructor({ url }: {
78
- url: string;
79
- });
80
- /**
81
- * Creates a new collection with the specified configuration.
82
- *
83
- * @param {string} indexName - The name of the collection to create.
84
- * @param {number} dimension - The dimension of the vectors to be stored in the collection.
85
- * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.
86
- * @returns {Promise<void>} A promise that resolves when the collection is created.
87
- */
88
- createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
89
- /**
90
- * Lists all indexes.
91
- *
92
- * @returns {Promise<string[]>} A promise that resolves to an array of indexes.
93
- */
94
- listIndexes(): Promise<string[]>;
95
- /**
96
- * Retrieves statistics about a vector index.
97
- *
98
- * @param {string} indexName - The name of the index to describe
99
- * @returns A promise that resolves to the index statistics including dimension, count and metric
100
- */
101
- describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats>;
102
- /**
103
- * Deletes the specified index.
104
- *
105
- * @param {string} indexName - The name of the index to delete.
106
- * @returns {Promise<void>} A promise that resolves when the index is deleted.
107
- */
108
- deleteIndex({ indexName }: DeleteIndexParams): Promise<void>;
109
- /**
110
- * Inserts or updates vectors in the specified collection.
111
- *
112
- * @param {string} indexName - The name of the collection to upsert into.
113
- * @param {number[][]} vectors - An array of vectors to upsert.
114
- * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.
115
- * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.
116
- * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.
117
- */
118
- upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
119
- /**
120
- * Queries the specified collection using a vector and optional filter.
121
- *
122
- * @param {string} indexName - The name of the collection to query.
123
- * @param {number[]} queryVector - The vector to query with.
124
- * @param {number} [topK] - The maximum number of results to return.
125
- * @param {Record<string, any>} [filter] - An optional filter to apply to the query. For more on filters in OpenSearch, see the filtering reference: https://opensearch.org/docs/latest/query-dsl/
126
- * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.
127
- * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.
128
- */
129
- query({ indexName, queryVector, filter, topK, includeVector, }: OpenSearchVectorParams): Promise<QueryResult[]>;
130
- /**
131
- * Validates the dimensions of the vectors.
132
- *
133
- * @param {number[][]} vectors - The vectors to validate.
134
- * @param {number} dimension - The dimension of the vectors.
135
- * @returns {void}
136
- */
137
- private validateVectorDimensions;
138
- /**
139
- * Transforms the filter to the OpenSearch DSL.
140
- *
141
- * @param {OpenSearchVectorFilter} filter - The filter to transform.
142
- * @returns {Record<string, any>} The transformed filter.
143
- */
144
- private transformFilter;
145
- /**
146
- * Updates a vector by its ID with the provided vector and/or metadata.
147
- * @param indexName - The name of the index containing the vector.
148
- * @param id - The ID of the vector to update.
149
- * @param update - An object containing the vector and/or metadata to update.
150
- * @param update.vector - An optional array of numbers representing the new vector.
151
- * @param update.metadata - An optional record containing the new metadata.
152
- * @returns A promise that resolves when the update is complete.
153
- * @throws Will throw an error if no updates are provided or if the update operation fails.
154
- */
155
- updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void>;
156
- /**
157
- * Deletes a vector by its ID.
158
- * @param indexName - The name of the index containing the vector.
159
- * @param id - The ID of the vector to delete.
160
- * @returns A promise that resolves when the deletion is complete.
161
- * @throws Will throw an error if the deletion operation fails.
162
- */
163
- deleteVector({ indexName, id }: DeleteVectorParams): Promise<void>;
164
- }
165
- export { OpenSearchVector }
166
- export { OpenSearchVector as OpenSearchVector_alias_1 }
167
-
168
- export declare type OpenSearchVectorFilter = VectorFilter<keyof OpenSearchOperatorValueMap, OpenSearchOperatorValueMap, OpenSearchLogicalOperatorValueMap, OpenSearchBlacklisted>;
169
-
170
- declare type OpenSearchVectorParams = QueryVectorParams<OpenSearchVectorFilter>;
171
-
172
- export { }
package/dist/index.d.cts DELETED
@@ -1 +0,0 @@
1
- export { OpenSearchVector } from './_tsup-dts-rollup.cjs';