@mastra/elasticsearch 1.0.0-beta.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,59 @@
1
1
  # @mastra/elasticsearch
2
2
 
3
+ ## 1.0.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Add ElasticSearch vector store support ([#10741](https://github.com/mastra-ai/mastra/pull/10741))
8
+
9
+ New `@mastra/elasticsearch` package providing vector similarity search using ElasticSearch 8.x+ with `dense_vector` fields.
10
+
11
+ ```typescript
12
+ import { ElasticSearchVector } from '@mastra/elasticsearch';
13
+
14
+ const vectorDB = new ElasticSearchVector({
15
+ url: 'http://localhost:9200',
16
+ id: 'my-vectors',
17
+ });
18
+
19
+ await vectorDB.createIndex({
20
+ indexName: 'embeddings',
21
+ dimension: 1536,
22
+ metric: 'cosine',
23
+ });
24
+
25
+ await vectorDB.upsert({
26
+ indexName: 'embeddings',
27
+ vectors: [embedding],
28
+ metadata: [{ source: 'doc.pdf' }],
29
+ });
30
+
31
+ const results = await vectorDB.query({
32
+ indexName: 'embeddings',
33
+ queryVector: queryEmbedding,
34
+ topK: 10,
35
+ filter: { source: 'doc.pdf' },
36
+ });
37
+ ```
38
+
39
+ ### Patch Changes
40
+
41
+ - Add embedded documentation support for Mastra packages ([#11472](https://github.com/mastra-ai/mastra/pull/11472))
42
+
43
+ Mastra packages now include embedded documentation in the published npm package under `dist/docs/`. This enables coding agents and AI assistants to understand and use the framework by reading documentation directly from `node_modules`.
44
+
45
+ Each package includes:
46
+ - **SKILL.md** - Entry point explaining the package's purpose and capabilities
47
+ - **SOURCE_MAP.json** - Machine-readable index mapping exports to types and implementation files
48
+ - **Topic folders** - Conceptual documentation organized by feature area
49
+
50
+ Documentation is driven by the `packages` frontmatter field in MDX files, which maps docs to their corresponding packages. CI validation ensures all docs include this field.
51
+
52
+ - Standardize error IDs across all storage and vector stores using centralized helper functions (`createStorageErrorId` and `createVectorErrorId`). This ensures consistent error ID patterns (`MASTRA_STORAGE_{STORE}_{OPERATION}_{STATUS}` and `MASTRA_VECTOR_{STORE}_{OPERATION}_{STATUS}`) across the codebase for better error tracking and debugging. ([#10913](https://github.com/mastra-ai/mastra/pull/10913))
53
+
54
+ - Updated dependencies [[`ac0d2f4`](https://github.com/mastra-ai/mastra/commit/ac0d2f4ff8831f72c1c66c2be809706d17f65789), [`2319326`](https://github.com/mastra-ai/mastra/commit/2319326f8c64e503a09bbcf14be2dd65405445e0), [`d2d3e22`](https://github.com/mastra-ai/mastra/commit/d2d3e22a419ee243f8812a84e3453dd44365ecb0), [`08766f1`](https://github.com/mastra-ai/mastra/commit/08766f15e13ac0692fde2a8bd366c2e16e4321df), [`72df8ae`](https://github.com/mastra-ai/mastra/commit/72df8ae595584cdd7747d5c39ffaca45e4507227), [`ebae12a`](https://github.com/mastra-ai/mastra/commit/ebae12a2dd0212e75478981053b148a2c246962d), [`c8417b4`](https://github.com/mastra-ai/mastra/commit/c8417b41d9f3486854dc7842d977fbe5e2166264), [`bc72b52`](https://github.com/mastra-ai/mastra/commit/bc72b529ee4478fe89ecd85a8be47ce0127b82a0), [`39c9743`](https://github.com/mastra-ai/mastra/commit/39c97432d084294f8ba85fbf3ef28098ff21459e), [`1dbd8c7`](https://github.com/mastra-ai/mastra/commit/1dbd8c729fb6536ec52f00064d76b80253d346e9), [`c61a0a5`](https://github.com/mastra-ai/mastra/commit/c61a0a5de4904c88fd8b3718bc26d1be1c2ec6e7), [`05b8bee`](https://github.com/mastra-ai/mastra/commit/05b8bee9e50e6c2a4a2bf210eca25ee212ca24fa), [`3076c67`](https://github.com/mastra-ai/mastra/commit/3076c6778b18988ae7d5c4c5c466366974b2d63f), [`3d93a15`](https://github.com/mastra-ai/mastra/commit/3d93a15796b158c617461c8b98bede476ebb43e2), [`9198899`](https://github.com/mastra-ai/mastra/commit/91988995c427b185c33714b7f3be955367911324), [`ed3e3dd`](https://github.com/mastra-ai/mastra/commit/ed3e3ddec69d564fe2b125e083437f76331f1283), [`c59e13c`](https://github.com/mastra-ai/mastra/commit/c59e13c7688284bd96b2baee3e314335003548de), [`c042bd0`](https://github.com/mastra-ai/mastra/commit/c042bd0b743e0e86199d0cb83344ca7690e34a9c), [`f743dbb`](https://github.com/mastra-ai/mastra/commit/f743dbb8b40d1627b5c10c0e6fc154f4ebb6e394), [`21a15de`](https://github.com/mastra-ai/mastra/commit/21a15de369fe82aac26bb642ed7be73505475e8b), [`e54953e`](https://github.com/mastra-ai/mastra/commit/e54953ed8ce1b28c0d62a19950163039af7834b4), [`ae8baf7`](https://github.com/mastra-ai/mastra/commit/ae8baf7d8adcb0ff9dac11880400452bc49b33ff), [`fec5129`](https://github.com/mastra-ai/mastra/commit/fec5129de7fc64423ea03661a56cef31dc747a0d), [`940a2b2`](https://github.com/mastra-ai/mastra/commit/940a2b27480626ed7e74f55806dcd2181c1dd0c2), [`1a0d3fc`](https://github.com/mastra-ai/mastra/commit/1a0d3fc811482c9c376cdf79ee615c23bae9b2d6), [`85d7ee1`](https://github.com/mastra-ai/mastra/commit/85d7ee18ff4e14d625a8a30ec6656bb49804989b), [`c6c1092`](https://github.com/mastra-ai/mastra/commit/c6c1092f8fbf76109303f69e000e96fd1960c4ce), [`0491e7c`](https://github.com/mastra-ai/mastra/commit/0491e7c9b714cb0ba22187ee062147ec2dd7c712), [`f6f4903`](https://github.com/mastra-ai/mastra/commit/f6f4903397314f73362061dc5a3e8e7c61ea34aa), [`d5ed981`](https://github.com/mastra-ai/mastra/commit/d5ed981c8701c1b8a27a5f35a9a2f7d9244e695f), [`85a628b`](https://github.com/mastra-ai/mastra/commit/85a628b1224a8f64cd82ea7f033774bf22df7a7e), [`0e8ed46`](https://github.com/mastra-ai/mastra/commit/0e8ed467c54d6901a6a365f270ec15d6faadb36c), [`33a4d2e`](https://github.com/mastra-ai/mastra/commit/33a4d2e4ed8af51f69256232f00c34d6b6b51d48), [`9650cce`](https://github.com/mastra-ai/mastra/commit/9650cce52a1d917ff9114653398e2a0f5c3ba808), [`6c049d9`](https://github.com/mastra-ai/mastra/commit/6c049d94063fdcbd5b81c4912a2bf82a92c9cc0b), [`910db9e`](https://github.com/mastra-ai/mastra/commit/910db9e0312888495eb5617b567f247d03303814), [`2f897df`](https://github.com/mastra-ai/mastra/commit/2f897df208508f46f51b7625e5dd20c37f93e0e3), [`d629361`](https://github.com/mastra-ai/mastra/commit/d629361a60f6565b5bfb11976fdaf7308af858e2), [`4f94ed8`](https://github.com/mastra-ai/mastra/commit/4f94ed8177abfde3ec536e3574883e075423350c), [`feb7ee4`](https://github.com/mastra-ai/mastra/commit/feb7ee4d09a75edb46c6669a3beaceec78811747), [`4aaa844`](https://github.com/mastra-ai/mastra/commit/4aaa844a4f19d054490f43638a990cc57bda8d2f), [`c237233`](https://github.com/mastra-ai/mastra/commit/c23723399ccedf7f5744b3f40997b79246bfbe64), [`38380b6`](https://github.com/mastra-ai/mastra/commit/38380b60fca905824bdf6b43df307a58efb1aa15), [`6833c69`](https://github.com/mastra-ai/mastra/commit/6833c69607418d257750bbcdd84638993d343539), [`932d63d`](https://github.com/mastra-ai/mastra/commit/932d63dd51be9c8bf1e00e3671fe65606c6fb9cd), [`4a1a6cb`](https://github.com/mastra-ai/mastra/commit/4a1a6cb3facad54b2bb6780b00ce91d6de1edc08), [`08c31c1`](https://github.com/mastra-ai/mastra/commit/08c31c188ebccd598acaf55e888b6397d01f7eae), [`919a22b`](https://github.com/mastra-ai/mastra/commit/919a22b25876f9ed5891efe5facbe682c30ff497), [`15f9e21`](https://github.com/mastra-ai/mastra/commit/15f9e216177201ea6e3f6d0bfb063fcc0953444f), [`3443770`](https://github.com/mastra-ai/mastra/commit/3443770662df8eb24c9df3589b2792d78cfcb811), [`69136e7`](https://github.com/mastra-ai/mastra/commit/69136e748e32f57297728a4e0f9a75988462f1a7), [`b0e2ea5`](https://github.com/mastra-ai/mastra/commit/b0e2ea5b52c40fae438b9e2f7baee6f0f89c5442), [`f0a07e0`](https://github.com/mastra-ai/mastra/commit/f0a07e0111b3307c5fabfa4094c5c2cfb734fbe6), [`ff94dea`](https://github.com/mastra-ai/mastra/commit/ff94dea935f4e34545c63bcb6c29804732698809), [`0d41fe2`](https://github.com/mastra-ai/mastra/commit/0d41fe245355dfc66d61a0d9c85d9400aac351ff), [`b760b73`](https://github.com/mastra-ai/mastra/commit/b760b731aca7c8a3f041f61d57a7f125ae9cb215), [`aaa40e7`](https://github.com/mastra-ai/mastra/commit/aaa40e788628b319baa8e889407d11ad626547fa), [`1521d71`](https://github.com/mastra-ai/mastra/commit/1521d716e5daedc74690c983fbd961123c56756b), [`449aed2`](https://github.com/mastra-ai/mastra/commit/449aed2ba9d507b75bf93d427646ea94f734dfd1), [`eb648a2`](https://github.com/mastra-ai/mastra/commit/eb648a2cc1728f7678768dd70cd77619b448dab9), [`695a621`](https://github.com/mastra-ai/mastra/commit/695a621528bdabeb87f83c2277cf2bb084c7f2b4), [`9e1911d`](https://github.com/mastra-ai/mastra/commit/9e1911db2b4db85e0e768c3f15e0d61e319869f6), [`ac3cc23`](https://github.com/mastra-ai/mastra/commit/ac3cc2397d1966bc0fc2736a223abc449d3c7719), [`c456e01`](https://github.com/mastra-ai/mastra/commit/c456e0149e3c176afcefdbd9bb1d2c5917723725), [`ebac155`](https://github.com/mastra-ai/mastra/commit/ebac15564a590117db7078233f927a7e28a85106), [`a86f4df`](https://github.com/mastra-ai/mastra/commit/a86f4df0407311e0d2ea49b9a541f0938810d6a9), [`dd1c38d`](https://github.com/mastra-ai/mastra/commit/dd1c38d1b75f1b695c27b40d8d9d6ed00d5e0f6f), [`5948e6a`](https://github.com/mastra-ai/mastra/commit/5948e6a5146c83666ba3f294b2be576c82a513fb), [`5b2ff46`](https://github.com/mastra-ai/mastra/commit/5b2ff4651df70c146523a7fca773f8eb0a2272f8), [`edb07e4`](https://github.com/mastra-ai/mastra/commit/edb07e49283e0c28bd094a60e03439bf6ecf0221), [`e0941c3`](https://github.com/mastra-ai/mastra/commit/e0941c3d7fc75695d5d258e7008fd5d6e650800c), [`db41688`](https://github.com/mastra-ai/mastra/commit/db4168806d007417e2e60b4f68656dca4e5f40c9), [`2b459f4`](https://github.com/mastra-ai/mastra/commit/2b459f466fd91688eeb2a44801dc23f7f8a887ab), [`798d0c7`](https://github.com/mastra-ai/mastra/commit/798d0c740232653b1d754870e6b43a55c364ffe2), [`0c0580a`](https://github.com/mastra-ai/mastra/commit/0c0580a42f697cd2a7d5973f25bfe7da9055038a), [`8940859`](https://github.com/mastra-ai/mastra/commit/89408593658199b4ad67f7b65e888f344e64a442), [`486352b`](https://github.com/mastra-ai/mastra/commit/486352b66c746602b68a95839f830de14c7fb8c0), [`ab035c2`](https://github.com/mastra-ai/mastra/commit/ab035c2ef6d8cc7bb25f06f1a38508bd9e6f126b), [`e629310`](https://github.com/mastra-ai/mastra/commit/e629310f1a73fa236d49ec7a1d1cceb6229dc7cc), [`0131105`](https://github.com/mastra-ai/mastra/commit/0131105532e83bdcbb73352fc7d0879eebf140dc), [`5ca599d`](https://github.com/mastra-ai/mastra/commit/5ca599d0bb59a1595f19f58473fcd67cc71cef58), [`09e4bae`](https://github.com/mastra-ai/mastra/commit/09e4bae18dd5357d2ae078a4a95a2af32168ab08), [`47b1c16`](https://github.com/mastra-ai/mastra/commit/47b1c16a01c7ffb6765fe1e499b49092f8b7eba3), [`4c6b492`](https://github.com/mastra-ai/mastra/commit/4c6b492c4dd591c6a592520c1f6855d6e936d71f), [`bff1145`](https://github.com/mastra-ai/mastra/commit/bff114556b3cbadad9b2768488708f8ad0e91475), [`dff01d8`](https://github.com/mastra-ai/mastra/commit/dff01d81ce1f4e4087cfac20fa868e6db138dd14), [`9d5059e`](https://github.com/mastra-ai/mastra/commit/9d5059eae810829935fb08e81a9bb7ecd5b144a7), [`ffe84d5`](https://github.com/mastra-ai/mastra/commit/ffe84d54f3b0f85167fe977efd027dba027eb998), [`5c8ca24`](https://github.com/mastra-ai/mastra/commit/5c8ca247094e0cc2cdbd7137822fb47241f86e77), [`9d819d5`](https://github.com/mastra-ai/mastra/commit/9d819d54b61481639f4008e4694791bddf187edd), [`24b76d8`](https://github.com/mastra-ai/mastra/commit/24b76d8e17656269c8ed09a0c038adb9cc2ae95a), [`31d13d5`](https://github.com/mastra-ai/mastra/commit/31d13d5fdc2e2380e2e3ee3ec9fb29d2a00f265d), [`ef756c6`](https://github.com/mastra-ai/mastra/commit/ef756c65f82d16531c43f49a27290a416611e526), [`e191844`](https://github.com/mastra-ai/mastra/commit/e1918444ca3f80e82feef1dad506cd4ec6e2875f), [`243a823`](https://github.com/mastra-ai/mastra/commit/243a8239c5906f5c94e4f78b54676793f7510ae3), [`b00ccd3`](https://github.com/mastra-ai/mastra/commit/b00ccd325ebd5d9e37e34dd0a105caae67eb568f), [`28f5f89`](https://github.com/mastra-ai/mastra/commit/28f5f89705f2409921e3c45178796c0e0d0bbb64), [`22553f1`](https://github.com/mastra-ai/mastra/commit/22553f11c63ee5e966a9c034a349822249584691), [`4c62166`](https://github.com/mastra-ai/mastra/commit/4c621669f4a29b1f443eca3ba70b814afa286266), [`e601b27`](https://github.com/mastra-ai/mastra/commit/e601b272c70f3a5ecca610373aa6223012704892), [`7d56d92`](https://github.com/mastra-ai/mastra/commit/7d56d9213886e8353956d7d40df10045fd12b299), [`81dc110`](https://github.com/mastra-ai/mastra/commit/81dc11008d147cf5bdc8996ead1aa61dbdebb6fc), [`7bcbf10`](https://github.com/mastra-ai/mastra/commit/7bcbf10133516e03df964b941f9a34e9e4ab4177), [`029540c`](https://github.com/mastra-ai/mastra/commit/029540ca1e582fc2dd8d288ecd4a9b0f31a954ef), [`7237163`](https://github.com/mastra-ai/mastra/commit/72371635dbf96a87df4b073cc48fc655afbdce3d), [`2500740`](https://github.com/mastra-ai/mastra/commit/2500740ea23da067d6e50ec71c625ab3ce275e64), [`4353600`](https://github.com/mastra-ai/mastra/commit/43536005a65988a8eede236f69122e7f5a284ba2), [`653e65a`](https://github.com/mastra-ai/mastra/commit/653e65ae1f9502c2958a32f47a5a2df11e612a92), [`873ecbb`](https://github.com/mastra-ai/mastra/commit/873ecbb517586aa17d2f1e99283755b3ebb2863f), [`6986fb0`](https://github.com/mastra-ai/mastra/commit/6986fb064f5db6ecc24aa655e1d26529087b43b3), [`3d3366f`](https://github.com/mastra-ai/mastra/commit/3d3366f31683e7137d126a3a57174a222c5801fb), [`5a4953f`](https://github.com/mastra-ai/mastra/commit/5a4953f7d25bb15ca31ed16038092a39cb3f98b3), [`4f9bbe5`](https://github.com/mastra-ai/mastra/commit/4f9bbe5968f42c86f4930b8193de3c3c17e5bd36), [`efe406a`](https://github.com/mastra-ai/mastra/commit/efe406a1353c24993280ebc2ed61dd9f65b84b26), [`eb9e522`](https://github.com/mastra-ai/mastra/commit/eb9e522ce3070a405e5b949b7bf5609ca51d7fe2), [`fd3d338`](https://github.com/mastra-ai/mastra/commit/fd3d338a2c362174ed5b383f1f011ad9fb0302aa), [`20e6f19`](https://github.com/mastra-ai/mastra/commit/20e6f1971d51d3ff6dd7accad8aaaae826d540ed), [`053e979`](https://github.com/mastra-ai/mastra/commit/053e9793b28e970086b0507f7f3b76ea32c1e838), [`02e51fe`](https://github.com/mastra-ai/mastra/commit/02e51feddb3d4155cfbcc42624fd0d0970d032c0), [`71c8d6c`](https://github.com/mastra-ai/mastra/commit/71c8d6c161253207b2b9588bdadb7eed604f7253), [`7aedb74`](https://github.com/mastra-ai/mastra/commit/7aedb74883adf66af38e270e4068fd42e7a37036), [`3bdfa75`](https://github.com/mastra-ai/mastra/commit/3bdfa7507a91db66f176ba8221aa28dd546e464a), [`119e5c6`](https://github.com/mastra-ai/mastra/commit/119e5c65008f3e5cfca954eefc2eb85e3bf40da4), [`c6fd6fe`](https://github.com/mastra-ai/mastra/commit/c6fd6fedd09e9cf8004b03a80925f5e94826ad7e), [`8f02d80`](https://github.com/mastra-ai/mastra/commit/8f02d800777397e4b45d7f1ad041988a8b0c6630), [`fdac646`](https://github.com/mastra-ai/mastra/commit/fdac646033a0930a1a4e00d13aa64c40bb7f1e02), [`6179a9b`](https://github.com/mastra-ai/mastra/commit/6179a9ba36ffac326de3cc3c43cdc8028d37c251), [`8f3fa3a`](https://github.com/mastra-ai/mastra/commit/8f3fa3a652bb77da092f913ec51ae46e3a7e27dc), [`d07b568`](https://github.com/mastra-ai/mastra/commit/d07b5687819ea8cb1dffa776d0c1765faf4aa1ae), [`e770de9`](https://github.com/mastra-ai/mastra/commit/e770de941a287a49b1964d44db5a5763d19890a6), [`e26dc9c`](https://github.com/mastra-ai/mastra/commit/e26dc9c3ccfec54ae3dc3e2b2589f741f9ae60a6), [`55edf73`](https://github.com/mastra-ai/mastra/commit/55edf7302149d6c964fbb7908b43babfc2b52145), [`c30400a`](https://github.com/mastra-ai/mastra/commit/c30400a49b994b1b97256fe785eb6c906fc2b232), [`486352b`](https://github.com/mastra-ai/mastra/commit/486352b66c746602b68a95839f830de14c7fb8c0), [`00f4921`](https://github.com/mastra-ai/mastra/commit/00f4921dd2c91a1e5446799599ef7116a8214a1a), [`1a46a56`](https://github.com/mastra-ai/mastra/commit/1a46a566f45a3fcbadc1cf36bf86d351f264bfa3), [`ca8041c`](https://github.com/mastra-ai/mastra/commit/ca8041cce0379fda22ed293a565bcb5b6ddca68a), [`b5dc973`](https://github.com/mastra-ai/mastra/commit/b5dc9733a5158850298dfb103acb3babdba8a318), [`7051bf3`](https://github.com/mastra-ai/mastra/commit/7051bf38b3b122a069008f861f7bfc004a6d9f6e), [`a8f1494`](https://github.com/mastra-ai/mastra/commit/a8f1494f4bbdc2770bcf327d4c7d869e332183f1), [`52e2716`](https://github.com/mastra-ai/mastra/commit/52e2716b42df6eff443de72360ae83e86ec23993), [`d7aad50`](https://github.com/mastra-ai/mastra/commit/d7aad501ce61646b76b4b511e558ac4eea9884d0), [`4f0b3c6`](https://github.com/mastra-ai/mastra/commit/4f0b3c66f196c06448487f680ccbb614d281e2f7), [`27b4040`](https://github.com/mastra-ai/mastra/commit/27b4040bfa1a95d92546f420a02a626b1419a1d6), [`c61fac3`](https://github.com/mastra-ai/mastra/commit/c61fac3add96f0dcce0208c07415279e2537eb62), [`6f14f70`](https://github.com/mastra-ai/mastra/commit/6f14f706ccaaf81b69544b6c1b75ab66a41e5317), [`69e0a87`](https://github.com/mastra-ai/mastra/commit/69e0a878896a2da9494945d86e056a5f8f05b851), [`cd29ad2`](https://github.com/mastra-ai/mastra/commit/cd29ad23a255534e8191f249593849ed29160886), [`bdf4d8c`](https://github.com/mastra-ai/mastra/commit/bdf4d8cdc656d8a2c21d81834bfa3bfa70f56c16), [`854e3da`](https://github.com/mastra-ai/mastra/commit/854e3dad5daac17a91a20986399d3a51f54bf68b), [`ce18d38`](https://github.com/mastra-ai/mastra/commit/ce18d38678c65870350d123955014a8432075fd9), [`3cf540b`](https://github.com/mastra-ai/mastra/commit/3cf540b9fbfea8f4fc8d3a2319a4e6c0b0cbfd52), [`352a5d6`](https://github.com/mastra-ai/mastra/commit/352a5d625cfe09849b21e8f52a24c9f0366759d5), [`1c6ce51`](https://github.com/mastra-ai/mastra/commit/1c6ce51f875915ab57fd36873623013699a2a65d), [`74c4f22`](https://github.com/mastra-ai/mastra/commit/74c4f22ed4c71e72598eacc346ba95cdbc00294f), [`3a76a80`](https://github.com/mastra-ai/mastra/commit/3a76a80284cb71a0faa975abb3d4b2a9631e60cd), [`898a972`](https://github.com/mastra-ai/mastra/commit/898a9727d286c2510d6b702dfd367e6aaf5c6b0f), [`0793497`](https://github.com/mastra-ai/mastra/commit/079349753620c40246ffd673e3f9d7d9820beff3), [`09e4bae`](https://github.com/mastra-ai/mastra/commit/09e4bae18dd5357d2ae078a4a95a2af32168ab08), [`026b848`](https://github.com/mastra-ai/mastra/commit/026b8483fbf5b6d977be8f7e6aac8d15c75558ac), [`2c212e7`](https://github.com/mastra-ai/mastra/commit/2c212e704c90e2db83d4109e62c03f0f6ebd2667), [`a97003a`](https://github.com/mastra-ai/mastra/commit/a97003aa1cf2f4022a41912324a1e77263b326b8), [`f9a2509`](https://github.com/mastra-ai/mastra/commit/f9a25093ea72d210a5e52cfcb3bcc8b5e02dc25c), [`66741d1`](https://github.com/mastra-ai/mastra/commit/66741d1a99c4f42cf23a16109939e8348ac6852e), [`ccc141e`](https://github.com/mastra-ai/mastra/commit/ccc141ed27da0abc3a3fc28e9e5128152e8e37f4), [`27c0009`](https://github.com/mastra-ai/mastra/commit/27c0009777a6073d7631b0eb7b481d94e165b5ca), [`01f8878`](https://github.com/mastra-ai/mastra/commit/01f88783de25e4de048c1c8aace43e26373c6ea5), [`dee388d`](https://github.com/mastra-ai/mastra/commit/dee388dde02f2e63c53385ae69252a47ab6825cc), [`610a70b`](https://github.com/mastra-ai/mastra/commit/610a70bdad282079f0c630e0d7bb284578f20151), [`5df9cce`](https://github.com/mastra-ai/mastra/commit/5df9cce1a753438413f64c11eeef8f845745c2a8), [`b7e17d3`](https://github.com/mastra-ai/mastra/commit/b7e17d3f5390bb5a71efc112204413656fcdc18d), [`4c77209`](https://github.com/mastra-ai/mastra/commit/4c77209e6c11678808b365d545845918c40045c8), [`a854ede`](https://github.com/mastra-ai/mastra/commit/a854ede62bf5ac0945a624ac48913dd69c73aabf), [`fe3b897`](https://github.com/mastra-ai/mastra/commit/fe3b897c2ccbcd2b10e81b099438c7337feddf89), [`c576fc0`](https://github.com/mastra-ai/mastra/commit/c576fc0b100b2085afded91a37c97a0ea0ec09c7), [`3defc80`](https://github.com/mastra-ai/mastra/commit/3defc80cf2b88a1b7fc1cc4ddcb91e982a614609), [`00123ba`](https://github.com/mastra-ai/mastra/commit/00123ba96dc9e5cd0b110420ebdba56d8f237b25), [`16153fe`](https://github.com/mastra-ai/mastra/commit/16153fe7eb13c99401f48e6ca32707c965ee28b9), [`9f4a683`](https://github.com/mastra-ai/mastra/commit/9f4a6833e88b52574665c028fd5508ad5c2f6004), [`bc94344`](https://github.com/mastra-ai/mastra/commit/bc943444a1342d8a662151b7bce1df7dae32f59c), [`4ca4306`](https://github.com/mastra-ai/mastra/commit/4ca430614daa5fa04730205a302a43bf4accfe9f), [`cccf9c8`](https://github.com/mastra-ai/mastra/commit/cccf9c8b2d2dfc1a5e63919395b83d78c89682a0), [`74e504a`](https://github.com/mastra-ai/mastra/commit/74e504a3b584eafd2f198001c6a113bbec589fd3), [`29c4309`](https://github.com/mastra-ai/mastra/commit/29c4309f818b24304c041bcb4a8f19b5f13f6b62), [`16785ce`](https://github.com/mastra-ai/mastra/commit/16785ced928f6f22638f4488cf8a125d99211799), [`57d157f`](https://github.com/mastra-ai/mastra/commit/57d157f0b163a95c3e6c9eae31bdb11d1bfc64f9), [`61a5705`](https://github.com/mastra-ai/mastra/commit/61a570551278b6743e64243b3ce7d73de915ca8a), [`903f67d`](https://github.com/mastra-ai/mastra/commit/903f67d184504a273893818c02b961f5423a79ad), [`3f3fc30`](https://github.com/mastra-ai/mastra/commit/3f3fc3096f24c4a26cffeecfe73085928f72aa63), [`d827d08`](https://github.com/mastra-ai/mastra/commit/d827d0808ffe1f3553a84e975806cc989b9735dd), [`e33fdbd`](https://github.com/mastra-ai/mastra/commit/e33fdbd07b33920d81e823122331b0c0bee0bb59), [`4524734`](https://github.com/mastra-ai/mastra/commit/45247343e384717a7c8404296275c56201d6470f), [`7a010c5`](https://github.com/mastra-ai/mastra/commit/7a010c56b846a313a49ae42fccd3d8de2b9f292d), [`2a90c55`](https://github.com/mastra-ai/mastra/commit/2a90c55a86a9210697d5adaab5ee94584b079adc), [`2a53598`](https://github.com/mastra-ai/mastra/commit/2a53598c6d8cfeb904a7fc74e57e526d751c8fa6), [`81b6a8f`](https://github.com/mastra-ai/mastra/commit/81b6a8ff79f49a7549d15d66624ac1a0b8f5f971), [`8538a0d`](https://github.com/mastra-ai/mastra/commit/8538a0d232619bf55dad7ddc2a8b0ca77c679a87), [`d90ea65`](https://github.com/mastra-ai/mastra/commit/d90ea6536f7aa51c6545a4e9215b55858e98e16d), [`db70a48`](https://github.com/mastra-ai/mastra/commit/db70a48aeeeeb8e5f92007e8ede52c364ce15287), [`261473a`](https://github.com/mastra-ai/mastra/commit/261473ac637e633064a22076671e2e02b002214d), [`eb09742`](https://github.com/mastra-ai/mastra/commit/eb09742197f66c4c38154c3beec78313e69760b2), [`de8239b`](https://github.com/mastra-ai/mastra/commit/de8239bdcb1d8c0cfa06da21f1569912a66bbc8a), [`e4d366a`](https://github.com/mastra-ai/mastra/commit/e4d366aeb500371dd4210d6aa8361a4c21d87034), [`23c10a1`](https://github.com/mastra-ai/mastra/commit/23c10a1efdd9a693c405511ab2dc8a1236603162), [`b5e6cd7`](https://github.com/mastra-ai/mastra/commit/b5e6cd77fc8c8e64e0494c1d06cee3d84e795d1e), [`d171e55`](https://github.com/mastra-ai/mastra/commit/d171e559ead9f52ec728d424844c8f7b164c4510), [`f0fdc14`](https://github.com/mastra-ai/mastra/commit/f0fdc14ee233d619266b3d2bbdeea7d25cfc6d13), [`a4f010b`](https://github.com/mastra-ai/mastra/commit/a4f010b22e4355a5fdee70a1fe0f6e4a692cc29e), [`c7cd3c7`](https://github.com/mastra-ai/mastra/commit/c7cd3c7a187d7aaf79e2ca139de328bf609a14b4), [`db18bc9`](https://github.com/mastra-ai/mastra/commit/db18bc9c3825e2c1a0ad9a183cc9935f6691bfa1), [`96d35f6`](https://github.com/mastra-ai/mastra/commit/96d35f61376bc2b1bf148648a2c1985bd51bef55), [`68ec97d`](https://github.com/mastra-ai/mastra/commit/68ec97d4c07c6393fcf95c2481fc5d73da99f8c8), [`8dc7f55`](https://github.com/mastra-ai/mastra/commit/8dc7f55900395771da851dc7d78d53ae84fe34ec), [`cfabdd4`](https://github.com/mastra-ai/mastra/commit/cfabdd4aae7a726b706942d6836eeca110fb6267), [`9b37b56`](https://github.com/mastra-ai/mastra/commit/9b37b565e1f2a76c24f728945cc740c2b09be9da), [`01b20fe`](https://github.com/mastra-ai/mastra/commit/01b20fefb7c67c2b7d79417598ef4e60256d1225), [`dd4f34c`](https://github.com/mastra-ai/mastra/commit/dd4f34c78cbae24063463475b0619575c415f9b8), [`8379099`](https://github.com/mastra-ai/mastra/commit/8379099fc467af6bef54dd7f80c9bd75bf8bbddf), [`0dbf199`](https://github.com/mastra-ai/mastra/commit/0dbf199110f22192ce5c95b1c8148d4872b4d119), [`5cbe88a`](https://github.com/mastra-ai/mastra/commit/5cbe88aefbd9f933bca669fd371ea36bf939ac6d), [`41a23c3`](https://github.com/mastra-ai/mastra/commit/41a23c32f9877d71810f37e24930515df2ff7a0f), [`a1bd7b8`](https://github.com/mastra-ai/mastra/commit/a1bd7b8571db16b94eb01588f451a74758c96d65), [`d78b38d`](https://github.com/mastra-ai/mastra/commit/d78b38d898fce285260d3bbb4befade54331617f), [`a0a5b4b`](https://github.com/mastra-ai/mastra/commit/a0a5b4bbebe6c701ebbadf744873aa0d5ca01371), [`ce0a73a`](https://github.com/mastra-ai/mastra/commit/ce0a73abeaa75b10ca38f9e40a255a645d50ebfb), [`5d171ad`](https://github.com/mastra-ai/mastra/commit/5d171ad9ef340387276b77c2bb3e83e83332d729), [`0633100`](https://github.com/mastra-ai/mastra/commit/0633100a911ad22f5256471bdf753da21c104742), [`3759cb0`](https://github.com/mastra-ai/mastra/commit/3759cb064935b5f74c65ac2f52a1145f7352899d), [`929f69c`](https://github.com/mastra-ai/mastra/commit/929f69c3436fa20dd0f0e2f7ebe8270bd82a1529), [`c710c16`](https://github.com/mastra-ai/mastra/commit/c710c1652dccfdc4111c8412bca7a6bb1d48b441), [`10c2735`](https://github.com/mastra-ai/mastra/commit/10c27355edfdad1ee2b826b897df74125eb81fb8), [`354ad0b`](https://github.com/mastra-ai/mastra/commit/354ad0b7b1b8183ac567f236a884fc7ede6d7138), [`cfae733`](https://github.com/mastra-ai/mastra/commit/cfae73394f4920635e6c919c8e95ff9a0788e2e5), [`8c0ec25`](https://github.com/mastra-ai/mastra/commit/8c0ec25646c8a7df253ed1e5ff4863a0d3f1316c), [`e3dfda7`](https://github.com/mastra-ai/mastra/commit/e3dfda7b11bf3b8c4bb55637028befb5f387fc74), [`69ea758`](https://github.com/mastra-ai/mastra/commit/69ea758358edd7117f191c2e69c8bb5fc79e7a1a), [`73b0bb3`](https://github.com/mastra-ai/mastra/commit/73b0bb394dba7c9482eb467a97ab283dbc0ef4db), [`651e772`](https://github.com/mastra-ai/mastra/commit/651e772eb1475fb13e126d3fcc01751297a88214), [`a02e542`](https://github.com/mastra-ai/mastra/commit/a02e542d23179bad250b044b17ff023caa61739f), [`f03ae60`](https://github.com/mastra-ai/mastra/commit/f03ae60500fe350c9d828621006cdafe1975fdd8), [`6b3ba91`](https://github.com/mastra-ai/mastra/commit/6b3ba91494cc10394df96782f349a4f7b1e152cc), [`a372c64`](https://github.com/mastra-ai/mastra/commit/a372c640ad1fd12e8f0613cebdc682fc156b4d95), [`993ad98`](https://github.com/mastra-ai/mastra/commit/993ad98d7ad3bebda9ecef5fec5c94349a0d04bc), [`676ccc7`](https://github.com/mastra-ai/mastra/commit/676ccc7fe92468d2d45d39c31a87825c89fd1ea0), [`3ff2c17`](https://github.com/mastra-ai/mastra/commit/3ff2c17a58e312fad5ea37377262c12d92ca0908), [`a0e437f`](https://github.com/mastra-ai/mastra/commit/a0e437fac561b28ee719e0302d72b2f9b4c138f0), [`d1e74a0`](https://github.com/mastra-ai/mastra/commit/d1e74a0a293866dece31022047f5dbab65a304d0), [`844ea5d`](https://github.com/mastra-ai/mastra/commit/844ea5dc0c248961e7bf73629ae7dcff503e853c), [`5627a8c`](https://github.com/mastra-ai/mastra/commit/5627a8c6dc11fe3711b3fa7a6ffd6eb34100a306), [`398fde3`](https://github.com/mastra-ai/mastra/commit/398fde3f39e707cda79372cdae8f9870e3b57c8d), [`c10398d`](https://github.com/mastra-ai/mastra/commit/c10398d5b88f1d4af556f4267ff06f1d11e89179), [`3ff45d1`](https://github.com/mastra-ai/mastra/commit/3ff45d10e0c80c5335a957ab563da72feb623520), [`f0f8f12`](https://github.com/mastra-ai/mastra/commit/f0f8f125c308f2d0fd36942ef652fd852df7522f), [`b61b93f`](https://github.com/mastra-ai/mastra/commit/b61b93f9e058b11dd2eec169853175d31dbdd567), [`bae33d9`](https://github.com/mastra-ai/mastra/commit/bae33d91a63fbb64d1e80519e1fc1acaed1e9013), [`39e7869`](https://github.com/mastra-ai/mastra/commit/39e7869bc7d0ee391077ce291474d8a84eedccff), [`0d7618b`](https://github.com/mastra-ai/mastra/commit/0d7618bc650bf2800934b243eca5648f4aeed9c2), [`7b763e5`](https://github.com/mastra-ai/mastra/commit/7b763e52fc3eaf699c2a99f2adf418dd46e4e9a5), [`251df45`](https://github.com/mastra-ai/mastra/commit/251df4531407dfa46d805feb40ff3fb49769f455), [`d36cfbb`](https://github.com/mastra-ai/mastra/commit/d36cfbbb6565ba5f827883cc9bb648eb14befdc1), [`f894d14`](https://github.com/mastra-ai/mastra/commit/f894d148946629af7b1f452d65a9cf864cec3765), [`8846867`](https://github.com/mastra-ai/mastra/commit/8846867ffa9a3746767618e314bebac08eb77d87), [`1924cf0`](https://github.com/mastra-ai/mastra/commit/1924cf06816e5e4d4d5333065ec0f4bb02a97799), [`c0b731f`](https://github.com/mastra-ai/mastra/commit/c0b731fb27d712dc8582e846df5c0332a6a0c5ba), [`5761926`](https://github.com/mastra-ai/mastra/commit/57619260c4a2cdd598763abbacd90de594c6bc76), [`c2b9547`](https://github.com/mastra-ai/mastra/commit/c2b9547bf435f56339f23625a743b2147ab1c7a6), [`3697853`](https://github.com/mastra-ai/mastra/commit/3697853deeb72017d90e0f38a93c1e29221aeca0), [`c900fdd`](https://github.com/mastra-ai/mastra/commit/c900fdd504c41348efdffb205cfe80d48c38fa33), [`9312dcd`](https://github.com/mastra-ai/mastra/commit/9312dcd1c6f5b321929e7d382e763d95fdc030f5), [`b2e45ec`](https://github.com/mastra-ai/mastra/commit/b2e45eca727a8db01a81ba93f1a5219c7183c839), [`5d7000f`](https://github.com/mastra-ai/mastra/commit/5d7000f757cd65ea9dc5b05e662fd83dfd44e932), [`43ca8f2`](https://github.com/mastra-ai/mastra/commit/43ca8f2c7334851cc7b4d3d2f037d8784bfbdd5f), [`d6d49f7`](https://github.com/mastra-ai/mastra/commit/d6d49f7b8714fa19a52ff9c7cf7fb7e73751901e), [`00c2387`](https://github.com/mastra-ai/mastra/commit/00c2387f5f04a365316f851e58666ac43f8c4edf), [`a534e95`](https://github.com/mastra-ai/mastra/commit/a534e9591f83b3cc1ebff99c67edf4cda7bf81d3), [`9d0e7fe`](https://github.com/mastra-ai/mastra/commit/9d0e7feca8ed98de959f53476ee1456073673348), [`53d927c`](https://github.com/mastra-ai/mastra/commit/53d927cc6f03bff33655b7e2b788da445a08731d), [`ad6250d`](https://github.com/mastra-ai/mastra/commit/ad6250dbdaad927e29f74a27b83f6c468b50a705), [`580b592`](https://github.com/mastra-ai/mastra/commit/580b5927afc82fe460dfdf9a38a902511b6b7e7f), [`604a79f`](https://github.com/mastra-ai/mastra/commit/604a79fecf276e26a54a3fe01bb94e65315d2e0e), [`42a42cf`](https://github.com/mastra-ai/mastra/commit/42a42cf3132b9786feecbb8c13c583dce5b0e198), [`3f2faf2`](https://github.com/mastra-ai/mastra/commit/3f2faf2e2d685d6c053cc5af1bf9fedf267b2ce5), [`22f64bc`](https://github.com/mastra-ai/mastra/commit/22f64bc1d37149480b58bf2fefe35b79a1e3e7d5), [`ff4d9a6`](https://github.com/mastra-ai/mastra/commit/ff4d9a6704fc87b31a380a76ed22736fdedbba5a), [`50fd320`](https://github.com/mastra-ai/mastra/commit/50fd320003d0d93831c230ef531bef41f5ba7b3a), [`847c212`](https://github.com/mastra-ai/mastra/commit/847c212caba7df0d6f2fc756b494ac3c75c3720d), [`69821ef`](https://github.com/mastra-ai/mastra/commit/69821ef806482e2c44e2197ac0b050c3fe3a5285), [`3a73998`](https://github.com/mastra-ai/mastra/commit/3a73998fa4ebeb7f3dc9301afe78095fc63e7999), [`ffa553a`](https://github.com/mastra-ai/mastra/commit/ffa553a3edc1bd17d73669fba66d6b6f4ac10897), [`83d5942`](https://github.com/mastra-ai/mastra/commit/83d5942669ce7bba4a6ca4fd4da697a10eb5ebdc), [`58e3931`](https://github.com/mastra-ai/mastra/commit/58e3931af9baa5921688566210f00fb0c10479fa), [`ae08bf0`](https://github.com/mastra-ai/mastra/commit/ae08bf0ebc6a4e4da992b711c4a389c32ba84cf4), [`0bed332`](https://github.com/mastra-ai/mastra/commit/0bed332843f627202c6520eaf671771313cd20f3), [`887f0b4`](https://github.com/mastra-ai/mastra/commit/887f0b4746cdbd7cb7d6b17ac9f82aeb58037ea5), [`2562143`](https://github.com/mastra-ai/mastra/commit/256214336b4faa78646c9c1776612393790d8784), [`b7959e6`](https://github.com/mastra-ai/mastra/commit/b7959e6e25a46b480f9ea2217c4c6c588c423791), [`a7ce182`](https://github.com/mastra-ai/mastra/commit/a7ce1822a8785ce45d62dd5c911af465e144f7d7), [`bda6370`](https://github.com/mastra-ai/mastra/commit/bda637009360649aaf579919e7873e33553c273e), [`d7acd8e`](https://github.com/mastra-ai/mastra/commit/d7acd8e987b5d7eff4fd98b0906c17c06a2e83d5), [`c7f1f7d`](https://github.com/mastra-ai/mastra/commit/c7f1f7d24f61f247f018cc2d1f33bf63212959a7), [`0bddc6d`](https://github.com/mastra-ai/mastra/commit/0bddc6d8dbd6f6008c0cba2e4960a2da75a55af1), [`bec5efd`](https://github.com/mastra-ai/mastra/commit/bec5efde96653ccae6604e68c696d1bc6c1a0bf5), [`5947fcd`](https://github.com/mastra-ai/mastra/commit/5947fcdd425531f29f9422026d466c2ee3113c93), [`4aa55b3`](https://github.com/mastra-ai/mastra/commit/4aa55b383cf06043943359ea316572fd969861a7), [`21735a7`](https://github.com/mastra-ai/mastra/commit/21735a7ef306963554a69a89b44f06c3bcd85141), [`735d8c1`](https://github.com/mastra-ai/mastra/commit/735d8c1c0d19fbc09e6f8b66cf41bc7655993838), [`7907fd1`](https://github.com/mastra-ai/mastra/commit/7907fd1c5059813b7b870b81ca71041dc807331b), [`1ed5716`](https://github.com/mastra-ai/mastra/commit/1ed5716830867b3774c4a1b43cc0d82935f32b96), [`acf322e`](https://github.com/mastra-ai/mastra/commit/acf322e0f1fd0189684cf529d91c694bea918a45), [`2ca67cc`](https://github.com/mastra-ai/mastra/commit/2ca67cc3bb1f6a617353fdcab197d9efebe60d6f), [`9eedf7d`](https://github.com/mastra-ai/mastra/commit/9eedf7de1d6e0022a2f4e5e9e6fe1ec468f9b43c), [`b339816`](https://github.com/mastra-ai/mastra/commit/b339816df0984d0243d944ac2655d6ba5f809cde), [`e16d553`](https://github.com/mastra-ai/mastra/commit/e16d55338403c7553531cc568125c63d53653dff), [`6f941c4`](https://github.com/mastra-ai/mastra/commit/6f941c438ca5f578619788acc7608fc2e23bd176), [`4186bdd`](https://github.com/mastra-ai/mastra/commit/4186bdd00731305726fa06adba0b076a1d50b49f), [`08bb631`](https://github.com/mastra-ai/mastra/commit/08bb631ae2b14684b2678e3549d0b399a6f0561e), [`c942802`](https://github.com/mastra-ai/mastra/commit/c942802a477a925b01859a7b8688d4355715caaa), [`4f0331a`](https://github.com/mastra-ai/mastra/commit/4f0331a79bf6eb5ee598a5086e55de4b5a0ada03), [`a0c8c1b`](https://github.com/mastra-ai/mastra/commit/a0c8c1b87d4fee252aebda73e8637fbe01d761c9), [`1d877b8`](https://github.com/mastra-ai/mastra/commit/1d877b8d7b536a251c1a7a18db7ddcf4f68d6f8b), [`cc34739`](https://github.com/mastra-ai/mastra/commit/cc34739c34b6266a91bea561119240a7acf47887), [`c218bd3`](https://github.com/mastra-ai/mastra/commit/c218bd3759e32423735b04843a09404572631014), [`9e67002`](https://github.com/mastra-ai/mastra/commit/9e67002b52c9be19936c420a489dbee9c5fd6a78), [`7aaf973`](https://github.com/mastra-ai/mastra/commit/7aaf973f83fbbe9521f1f9e7a4fd99b8de464617), [`2c4438b`](https://github.com/mastra-ai/mastra/commit/2c4438b87817ab7eed818c7990fef010475af1a3), [`35edc49`](https://github.com/mastra-ai/mastra/commit/35edc49ac0556db609189641d6341e76771b81fc), [`4d59f58`](https://github.com/mastra-ai/mastra/commit/4d59f58de2d90d6e2810a19d4518e38ddddb9038), [`ef11a61`](https://github.com/mastra-ai/mastra/commit/ef11a61920fa0ed08a5b7ceedd192875af119749), [`2b8893c`](https://github.com/mastra-ai/mastra/commit/2b8893cb108ef9acb72ee7835cd625610d2c1a4a), [`8e5c75b`](https://github.com/mastra-ai/mastra/commit/8e5c75bdb1d08a42d45309a4c72def4b6890230f), [`e1bb9c9`](https://github.com/mastra-ai/mastra/commit/e1bb9c94b4eb68b019ae275981be3feb769b5365), [`351a11f`](https://github.com/mastra-ai/mastra/commit/351a11fcaf2ed1008977fa9b9a489fc422e51cd4), [`8a73529`](https://github.com/mastra-ai/mastra/commit/8a73529ca01187f604b1f3019d0a725ac63ae55f), [`e59e0d3`](https://github.com/mastra-ai/mastra/commit/e59e0d32afb5fcf2c9f3c00c8f81f6c21d3a63fa), [`4fba91b`](https://github.com/mastra-ai/mastra/commit/4fba91bec7c95911dc28e369437596b152b04cd0), [`465ac05`](https://github.com/mastra-ai/mastra/commit/465ac0526a91d175542091c675181f1a96c98c46), [`fa8409b`](https://github.com/mastra-ai/mastra/commit/fa8409bc39cfd8ba6643b9db5269b90b22e2a2f7), [`8a000da`](https://github.com/mastra-ai/mastra/commit/8a000da0c09c679a2312f6b3aa05b2ca78ca7393), [`e7266a2`](https://github.com/mastra-ai/mastra/commit/e7266a278db02035c97a5e9cd9d1669a6b7a535d), [`173c535`](https://github.com/mastra-ai/mastra/commit/173c535c0645b0da404fe09f003778f0b0d4e019), [`12b0cc4`](https://github.com/mastra-ai/mastra/commit/12b0cc4077d886b1a552637dedb70a7ade93528c), [`3bf6c5f`](https://github.com/mastra-ai/mastra/commit/3bf6c5f104c25226cd84e0c77f9dec15f2cac2db)]:
55
+ - @mastra/core@1.0.0
56
+
3
57
  ## 1.0.0-beta.4
4
58
 
5
59
  ### Patch Changes
@@ -29,4 +29,4 @@ docs/
29
29
  ## Version
30
30
 
31
31
  Package: @mastra/elasticsearch
32
- Version: 1.0.0-beta.4
32
+ Version: 1.0.0
@@ -5,7 +5,7 @@ description: Documentation for @mastra/elasticsearch. Includes links to type def
5
5
 
6
6
  # @mastra/elasticsearch Documentation
7
7
 
8
- > **Version**: 1.0.0-beta.4
8
+ > **Version**: 1.0.0
9
9
  > **Package**: @mastra/elasticsearch
10
10
 
11
11
  ## Quick Navigation
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.0-beta.4",
2
+ "version": "1.0.0",
3
3
  "package": "@mastra/elasticsearch",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -12,6 +12,7 @@ After generating embeddings, you need to store them in a database that supports
12
12
  import { MongoDBVector } from "@mastra/mongodb";
13
13
 
14
14
  const store = new MongoDBVector({
15
+ id: 'mongodb-vector',
15
16
  uri: process.env.MONGODB_URI,
16
17
  dbName: process.env.MONGODB_DATABASE,
17
18
  });
@@ -26,7 +27,7 @@ await store.upsert({
26
27
  });
27
28
  ```
28
29
 
29
- ### Using MongoDB Atlas Vector search
30
+ <h3>Using MongoDB Atlas Vector search</h3>
30
31
 
31
32
  For detailed setup instructions and best practices, see the [official MongoDB Atlas Vector Search documentation](https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-overview/?utm_campaign=devrel&utm_source=third-party-content&utm_medium=cta&utm_content=mastra-docs).
32
33
 
@@ -54,7 +55,7 @@ await store.upsert({
54
55
  });
55
56
  ```
56
57
 
57
- ### Using PostgreSQL with pgvector
58
+ <h3>Using PostgreSQL with pgvector</h3>
58
59
 
59
60
  PostgreSQL with the pgvector extension is a good solution for teams already using PostgreSQL who want to minimize infrastructure complexity.
60
61
  For detailed setup instructions and best practices, see the [official pgvector repository](https://github.com/pgvector/pgvector).
@@ -144,6 +145,7 @@ await store.upsert({
144
145
  import { AstraVector } from "@mastra/astra";
145
146
 
146
147
  const store = new AstraVector({
148
+ id: 'astra-vector',
147
149
  token: process.env.ASTRA_DB_TOKEN,
148
150
  endpoint: process.env.ASTRA_DB_ENDPOINT,
149
151
  keyspace: process.env.ASTRA_DB_KEYSPACE,
@@ -170,7 +172,7 @@ import { LibSQLVector } from "@mastra/core/vector/libsql";
170
172
 
171
173
  const store = new LibSQLVector({
172
174
  id: 'libsql-vector',
173
- connectionUrl: process.env.DATABASE_URL,
175
+ url: process.env.DATABASE_URL,
174
176
  authToken: process.env.DATABASE_AUTH_TOKEN, // Optional: for Turso cloud databases
175
177
  });
176
178
 
@@ -217,6 +219,7 @@ await store.upsert({
217
219
  import { CloudflareVector } from "@mastra/vectorize";
218
220
 
219
221
  const store = new CloudflareVector({
222
+ id: 'cloudflare-vector',
220
223
  accountId: process.env.CF_ACCOUNT_ID,
221
224
  apiToken: process.env.CF_API_TOKEN,
222
225
  });
@@ -238,7 +241,7 @@ await store.upsert({
238
241
  ```ts title="vector-store.ts"
239
242
  import { OpenSearchVector } from "@mastra/opensearch";
240
243
 
241
- const store = new OpenSearchVector({ url: process.env.OPENSEARCH_URL });
244
+ const store = new OpenSearchVector({ id: "opensearch", node: process.env.OPENSEARCH_URL });
242
245
 
243
246
  await store.createIndex({
244
247
  indexName: "my-collection",
@@ -259,7 +262,7 @@ await store.upsert({
259
262
  ```ts title="vector-store.ts"
260
263
  import { ElasticSearchVector } from "@mastra/elasticsearch";
261
264
 
262
- const store = new ElasticSearchVector({ url: process.env.ELASTICSEARCH_URL });
265
+ const store = new ElasticSearchVector({ id: 'elasticsearch-vector', url: process.env.ELASTICSEARCH_URL });
263
266
 
264
267
  await store.createIndex({
265
268
  indexName: "my-collection",
@@ -280,6 +283,7 @@ await store.upsert({
280
283
  import { CouchbaseVector } from "@mastra/couchbase";
281
284
 
282
285
  const store = new CouchbaseVector({
286
+ id: 'couchbase-vector',
283
287
  connectionString: process.env.COUCHBASE_CONNECTION_STRING,
284
288
  username: process.env.COUCHBASE_USERNAME,
285
289
  password: process.env.COUCHBASE_PASSWORD,
@@ -319,7 +323,7 @@ await store.upsert({
319
323
  });
320
324
  ```
321
325
 
322
- ### Using LanceDB
326
+ <h3>Using LanceDB</h3>
323
327
 
324
328
  LanceDB is an embedded vector database built on the Lance columnar format, suitable for local development or cloud deployment.
325
329
  For detailed setup instructions and best practices, see the [official LanceDB documentation](https://lancedb.github.io/lancedb/).
@@ -331,6 +335,7 @@ For detailed setup instructions and best practices, see the [official LanceDB do
331
335
  import { S3Vectors } from "@mastra/s3vectors";
332
336
 
333
337
  const store = new S3Vectors({
338
+ id: 's3-vectors',
334
339
  vectorBucketName: "my-vector-bucket",
335
340
  clientConfig: {
336
341
  region: "us-east-1",
@@ -373,7 +378,7 @@ The dimension size must match the output dimension of your chosen embedding mode
373
378
  - Cohere embed-multilingual-v3: 1024 dimensions
374
379
  - Google text-embedding-004: 768 dimensions (or custom)
375
380
 
376
- important
381
+ > **Note:**
377
382
  Index dimensions cannot be changed after creation. To use a different model, delete and recreate the index with the new dimension size.
378
383
 
379
384
  ### Naming Rules for Databases
@@ -537,7 +542,7 @@ The upsert operation:
537
542
 
538
543
  Vector stores support rich metadata (any JSON-serializable fields) for filtering and organization. Since metadata is stored with no fixed schema, use consistent field naming to avoid unexpected query results.
539
544
 
540
- important
545
+ > **Note:**
541
546
  Metadata is crucial for vector storage - without it, you'd only have numerical embeddings with no way to return the original text or filter results. Always store at least the source text as metadata.
542
547
 
543
548
  ```ts
@@ -24,6 +24,7 @@ npm install @mastra/elasticsearch@beta
24
24
  import { ElasticSearchVector } from "@mastra/elasticsearch";
25
25
 
26
26
  const store = new ElasticSearchVector({
27
+ id: "elasticsearch-vector",
27
28
  url: process.env.ELASTICSEARCH_URL,
28
29
  });
29
30
 
package/dist/index.cjs CHANGED
@@ -145,8 +145,18 @@ var ElasticSearchFilterTranslator = class extends filter.BaseFilterTranslator {
145
145
  const fieldWithKeyword2 = this.addKeywordIfNeeded(field, value);
146
146
  switch (operator) {
147
147
  case "$eq":
148
+ if (value === null) {
149
+ return {
150
+ bool: {
151
+ must_not: [{ exists: { field } }]
152
+ }
153
+ };
154
+ }
148
155
  return { term: { [fieldWithKeyword2]: normalizedValue } };
149
156
  case "$ne":
157
+ if (value === null) {
158
+ return { exists: { field } };
159
+ }
150
160
  return {
151
161
  bool: {
152
162
  must_not: [{ term: { [fieldWithKeyword2]: normalizedValue } }]
@@ -556,6 +566,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
556
566
  * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.
557
567
  */
558
568
  async upsert({ indexName, vectors, metadata = [], ids }) {
569
+ vector.validateUpsert("ELASTICSEARCH", vectors, metadata, ids, true);
559
570
  const vectorIds = ids || vectors.map(() => crypto.randomUUID());
560
571
  const operations = [];
561
572
  try {
@@ -660,6 +671,7 @@ var ElasticSearchVector = class extends vector.MastraVector {
660
671
  topK = 10,
661
672
  includeVector = false
662
673
  }) {
674
+ vector.validateTopK("ELASTICSEARCH", topK);
663
675
  try {
664
676
  const translatedFilter = this.transformFilter(filter);
665
677
  const response = await this.client.search({
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["BaseFilterTranslator","fieldWithKeyword","MastraVector","ElasticSearchClient","MastraError","createVectorErrorId","ErrorDomain","ErrorCategory","error"],"mappings":";;;;;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4CA,2BAAA,CAAgD;AAAA,EAC9E,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAGA,2BAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAM,CAAA;AAAA,MAC/B,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,KAAA,EAAO,CAAC,QAAQ,CAAA;AAAA,MAChB,QAAQ;AAAC,KACX;AAAA,EACF;AAAA,EAEA,UAAU,MAAA,EAA+D;AACvE,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAO,MAAA;AACjC,IAAA,IAAA,CAAK,eAAe,MAAM,CAAA;AAC1B,IAAA,OAAO,IAA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,eAAA,EAAiB,gBAAA,EAAkB,QAAQ,CAAA;AAAA,UACnE,QAAQC,iBAAA,CAAY,OAAA;AAAA,UACpB,UAAUC,mBAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACAC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { createVectorErrorId } from '@mastra/core/storage';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'INVALID_ARGS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'LIST_INDEXES', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'FETCH_FAILED'),\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'DIMENSION_MISMATCH'),\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'QUERY', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_UPDATES'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR_BY_FILTER', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\n },\n },\n error,\n );\n }\n }\n\n /**\n * Deletes a vector by its ID.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to delete.\n * @returns A promise that resolves when the deletion is complete.\n * @throws Will throw an error if the deletion operation fails.\n */\n async deleteVector({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_IDS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["BaseFilterTranslator","fieldWithKeyword","MastraVector","ElasticSearchClient","MastraError","createVectorErrorId","ErrorDomain","ErrorCategory","error","validateUpsert","validateTopK"],"mappings":";;;;;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4CA,2BAAA,CAAgD;AAAA,EAC9E,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAGA,2BAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAM,CAAA;AAAA,MAC/B,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,KAAA,EAAO,CAAC,QAAQ,CAAA;AAAA,MAChB,QAAQ;AAAC,KACX;AAAA,EACF;AAAA,EAEA,UAAU,MAAA,EAA+D;AACvE,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAO,MAAA;AACjC,IAAA,IAAA,CAAK,eAAe,MAAM,CAAA;AAC1B,IAAA,OAAO,IAAA,CAAK,cAAc,MAAM,CAAA;AAAA,EAClC;AAAA,EAEQ,cAAc,IAAA,EAAsC;AAE1D,IAAA,IAAI,KAAK,WAAA,CAAY,IAAI,KAAK,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjD,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,IAA2B,CAAA;AAG1D,IAAA,MAAM,mBAAoC,EAAC;AAC3C,IAAA,MAAM,kBAAmC,EAAC;AAE1C,IAAA,OAAA,CAAQ,OAAA,CAAQ,CAAC,CAAC,GAAA,EAAK,KAAK,CAAA,KAAM;AAChC,MAAA,IAAI,IAA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AAQ,CAAA;AAAA,UACnE,QAAQC,iBAAA,CAAY,OAAA;AAAA,UACpB,UAAUC,mBAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACAC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n // Handle null equality: field does not exist or is null\n if (value === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n // Handle null inequality: field exists (i.e., is not null)\n if (value === null) {\n return { exists: { field } };\n }\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { createVectorErrorId } from '@mastra/core/storage';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector, validateUpsert, validateTopK } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'INVALID_ARGS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'LIST_INDEXES', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'FETCH_FAILED'),\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'DIMENSION_MISMATCH'),\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n // Validate input parameters and vector values\n validateUpsert('ELASTICSEARCH', vectors, metadata, ids, true);\n\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n // Validate topK parameter\n validateTopK('ELASTICSEARCH', topK);\n\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'QUERY', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_UPDATES'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR_BY_FILTER', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\n },\n },\n error,\n );\n }\n }\n\n /**\n * Deletes a vector by its ID.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to delete.\n * @returns A promise that resolves when the deletion is complete.\n * @throws Will throw an error if the deletion operation fails.\n */\n async deleteVector({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_IDS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Client } from '@elastic/elasticsearch';
2
2
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
3
  import { createVectorErrorId } from '@mastra/core/storage';
4
- import { MastraVector } from '@mastra/core/vector';
4
+ import { MastraVector, validateUpsert, validateTopK } from '@mastra/core/vector';
5
5
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
6
6
 
7
7
  // src/vector/index.ts
@@ -143,8 +143,18 @@ var ElasticSearchFilterTranslator = class extends BaseFilterTranslator {
143
143
  const fieldWithKeyword2 = this.addKeywordIfNeeded(field, value);
144
144
  switch (operator) {
145
145
  case "$eq":
146
+ if (value === null) {
147
+ return {
148
+ bool: {
149
+ must_not: [{ exists: { field } }]
150
+ }
151
+ };
152
+ }
146
153
  return { term: { [fieldWithKeyword2]: normalizedValue } };
147
154
  case "$ne":
155
+ if (value === null) {
156
+ return { exists: { field } };
157
+ }
148
158
  return {
149
159
  bool: {
150
160
  must_not: [{ term: { [fieldWithKeyword2]: normalizedValue } }]
@@ -554,6 +564,7 @@ var ElasticSearchVector = class extends MastraVector {
554
564
  * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.
555
565
  */
556
566
  async upsert({ indexName, vectors, metadata = [], ids }) {
567
+ validateUpsert("ELASTICSEARCH", vectors, metadata, ids, true);
557
568
  const vectorIds = ids || vectors.map(() => crypto.randomUUID());
558
569
  const operations = [];
559
570
  try {
@@ -658,6 +669,7 @@ var ElasticSearchVector = class extends MastraVector {
658
669
  topK = 10,
659
670
  includeVector = false
660
671
  }) {
672
+ validateTopK("ELASTICSEARCH", topK);
661
673
  try {
662
674
  const translatedFilter = this.transformFilter(filter);
663
675
  const response = await this.client.search({
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["fieldWithKeyword","ElasticSearchClient"],"mappings":";;;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4C,oBAAA,CAAgD;AAAA,EAC9E,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAG,oBAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAM,CAAA;AAAA,MAC/B,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,KAAA,EAAO,CAAC,QAAQ,CAAA;AAAA,MAChB,QAAQ;AAAC,KACX;AAAA,EACF;AAAA,EAEA,UAAU,MAAA,EAA+D;AACvE,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAO,MAAA;AACjC,IAAA,IAAA,CAAK,eAAe,MAAM,CAAA;AAC1B,IAAA,OAAO,IAAA,CAAK,cAAc,MAAM,CAAA;AAAA,EAClC;AAAA,EAEQ,cAAc,IAAA,EAAsC;AAE1D,IAAA,IAAI,KAAK,WAAA,CAAY,IAAI,KAAK,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjD,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,IAA2B,CAAA;AAG1D,IAAA,MAAM,mBAAoC,EAAC;AAC3C,IAAA,MAAM,kBAAmC,EAAC;AAE1C,IAAA,OAAA,CAAQ,OAAA,CAAQ,CAAC,CAAC,GAAA,EAAK,KAAK,CAAA,KAAM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;AACzC,YAAA,IAAA,CAAK,MAAA,EAAQ,eAAe,WAAW,CAAA;AAGvC,YAAA,MAAM,WAAA;AAAA,UACR;AAAA,QACF;AAAA,MACF,WAAW,MAAA,EAAQ;AAEjB,QAAA,MAAM,UAAA,GAAa,IAAI,6BAAA,EAA8B;AACrD,QAAA,MAAM,gBAAA,GAAmB,UAAA,CAAW,SAAA,CAAU,MAAM,CAAA;AAEpD,QAAA,MAAM,IAAA,CAAK,OAAO,aAAA,CAAc;AAAA,UAC9B,KAAA,EAAO,SAAA;AAAA,UACP,KAAA,EAAQ,gBAAA,IAA4B,EAAE,SAAA,EAAW,EAAC,EAAE;AAAA,UACpD,OAAA,EAAS;AAAA,SACV,CAAA;AAAA,MACH;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,KAAA,YAAiB,aAAa,MAAM,KAAA;AACxC,MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,mBAAA,CAAoB,eAAA,EAAiB,gBAAA,EAAkB,QAAQ,CAAA;AAAA,UACnE,QAAQ,WAAA,CAAY,OAAA;AAAA,UACpB,UAAU,aAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { createVectorErrorId } from '@mastra/core/storage';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'INVALID_ARGS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'LIST_INDEXES', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'FETCH_FAILED'),\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'DIMENSION_MISMATCH'),\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'QUERY', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_UPDATES'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR_BY_FILTER', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\n },\n },\n error,\n );\n }\n }\n\n /**\n * Deletes a vector by its ID.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to delete.\n * @returns A promise that resolves when the deletion is complete.\n * @throws Will throw an error if the deletion operation fails.\n */\n async deleteVector({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_IDS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["fieldWithKeyword","ElasticSearchClient"],"mappings":";;;;;;;AA4BO,IAAM,6BAAA,GAAN,cAA4C,oBAAA,CAAgD;AAAA,EAC9E,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAG,oBAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAM,CAAA;AAAA,MAC/B,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,KAAA,EAAO,CAAC,QAAQ,CAAA;AAAA,MAChB,QAAQ;AAAC,KACX;AAAA,EACF;AAAA,EAEA,UAAU,MAAA,EAA+D;AACvE,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA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SAAA;AAAA,UACP,KAAA,EAAQ,gBAAA,IAA4B,EAAE,SAAA,EAAW,EAAC,EAAE;AAAA,UACpD,OAAA,EAAS;AAAA,SACV,CAAA;AAAA,MACH;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,KAAA,YAAiB,aAAa,MAAM,KAAA;AACxC,MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,mBAAA,CAAoB,eAAA,EAAiB,gBAAA,EAAkB,QAAQ,CAAA;AAAA,UACnE,QAAQ,WAAA,CAAY,OAAA;AAAA,UACpB,UAAU,aAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,SAAA;AAAA,YACA,GAAI,MAAA,IAAU,EAAE,QAAQ,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EAAE;AAAA,YAC/C,GAAI,GAAA,IAAO,EAAE,QAAA,EAAU,IAAI,MAAA;AAAO;AACpC,SACF;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type {\n BlacklistedRootOperators,\n LogicalOperatorValueMap,\n OperatorSupport,\n OperatorValueMap,\n QueryOperator,\n VectorFilter,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\n\ntype ElasticSearchOperatorValueMap = Omit<OperatorValueMap, '$options' | '$nor' | '$elemMatch'>;\n\ntype ElasticSearchLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor'>;\n\ntype ElasticSearchBlacklisted = BlacklistedRootOperators | '$nor';\n\nexport type ElasticSearchVectorFilter = VectorFilter<\n keyof ElasticSearchOperatorValueMap,\n ElasticSearchOperatorValueMap,\n ElasticSearchLogicalOperatorValueMap,\n ElasticSearchBlacklisted\n>;\n\n/**\n * Translator for ElasticSearch filter queries.\n * Maintains ElasticSearch-compatible syntax while ensuring proper validation\n * and normalization of values.\n */\nexport class ElasticSearchFilterTranslator extends BaseFilterTranslator<ElasticSearchVectorFilter> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or', '$not'],\n array: ['$in', '$nin', '$all'],\n regex: ['$regex'],\n custom: [],\n };\n }\n\n translate(filter?: ElasticSearchVectorFilter): ElasticSearchVectorFilter {\n if (this.isEmpty(filter)) return undefined;\n this.validateFilter(filter);\n return this.translateNode(filter);\n }\n\n private translateNode(node: ElasticSearchVectorFilter): any {\n // Handle primitive values and arrays\n if (this.isPrimitive(node) || Array.isArray(node)) {\n return node;\n }\n\n const entries = Object.entries(node as Record<string, any>);\n\n // Extract logical operators and field conditions\n const logicalOperators: [string, any][] = [];\n const fieldConditions: [string, any][] = [];\n\n entries.forEach(([key, value]) => {\n if (this.isLogicalOperator(key)) {\n logicalOperators.push([key, value]);\n } else {\n fieldConditions.push([key, value]);\n }\n });\n\n // If we have a single logical operator\n if (logicalOperators.length === 1 && fieldConditions.length === 0) {\n const [operator, value] = logicalOperators[0] as [QueryOperator, any];\n if (!Array.isArray(value) && typeof value !== 'object') {\n throw new Error(`Invalid logical operator structure: ${operator} must have an array or object value`);\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // Process field conditions\n const fieldConditionQueries = fieldConditions.map(([key, value]) => {\n // Handle nested objects\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Check if the object contains operators\n const hasOperators = Object.keys(value).some(k => this.isOperator(k));\n\n // Use a more direct approach based on whether operators are present\n const nestedField = `metadata.${key}`;\n return hasOperators\n ? this.translateFieldConditions(nestedField, value)\n : this.translateNestedObject(nestedField, value);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { terms: { [fieldWithKeyword]: value } };\n }\n\n // Handle simple field equality\n const fieldWithKeyword = this.addKeywordIfNeeded(`metadata.${key}`, value);\n return { term: { [fieldWithKeyword]: value } };\n });\n\n // Handle case with both logical operators and field conditions or multiple logical operators\n if (logicalOperators.length > 0) {\n const logicalConditions = logicalOperators.map(([operator, value]) =>\n this.translateOperator(operator as QueryOperator, value),\n );\n\n return {\n bool: {\n must: [...logicalConditions, ...fieldConditionQueries],\n },\n };\n }\n\n // If we only have field conditions\n if (fieldConditionQueries.length > 1) {\n return {\n bool: {\n must: fieldConditionQueries,\n },\n };\n }\n\n // If we have only one field condition\n if (fieldConditionQueries.length === 1) {\n return fieldConditionQueries[0];\n }\n\n // If we have no conditions (e.g., only empty $and arrays)\n return { match_all: {} };\n }\n\n /**\n * Handles translation of nested objects with dot notation fields\n */\n private translateNestedObject(field: string, value: Record<string, any>): any {\n const conditions = Object.entries(value).map(([subField, subValue]) => {\n const fullField = `${field}.${subField}`;\n\n // Check if this is an operator in a nested field\n if (this.isOperator(subField)) {\n return this.translateOperator(subField as QueryOperator, subValue, field);\n }\n\n if (typeof subValue === 'object' && subValue !== null && !Array.isArray(subValue)) {\n // Check if the nested object contains operators\n const hasOperators = Object.keys(subValue).some(k => this.isOperator(k));\n if (hasOperators) {\n return this.translateFieldConditions(fullField, subValue);\n }\n return this.translateNestedObject(fullField, subValue);\n }\n const fieldWithKeyword = this.addKeywordIfNeeded(fullField, subValue);\n return { term: { [fieldWithKeyword]: subValue } };\n });\n\n return {\n bool: {\n must: conditions,\n },\n };\n }\n\n private translateLogicalOperator(operator: QueryOperator, value: any): any {\n const conditions = Array.isArray(value) ? value.map(item => this.translateNode(item)) : [this.translateNode(value)];\n switch (operator) {\n case '$and':\n // For empty $and, return a query that matches everything\n if (Array.isArray(value) && value.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must: conditions,\n },\n };\n case '$or':\n // For empty $or, return a query that matches nothing\n if (Array.isArray(value) && value.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n should: conditions,\n minimum_should_match: 1,\n },\n };\n case '$not':\n return {\n bool: {\n must_not: conditions,\n },\n };\n default:\n return value;\n }\n }\n\n private translateFieldOperator(field: string, operator: QueryOperator, value: any): any {\n // Handle basic comparison operators\n if (this.isBasicOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$eq':\n // Handle null equality: field does not exist or is null\n if (value === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n return { term: { [fieldWithKeyword]: normalizedValue } };\n case '$ne':\n // Handle null inequality: field exists (i.e., is not null)\n if (value === null) {\n return { exists: { field } };\n }\n return {\n bool: {\n must_not: [{ term: { [fieldWithKeyword]: normalizedValue } }],\n },\n };\n default:\n return { term: { [fieldWithKeyword]: normalizedValue } };\n }\n }\n\n // Handle numeric operators\n if (this.isNumericOperator(operator)) {\n const normalizedValue = this.normalizeComparisonValue(value);\n const rangeOp = operator.replace('$', '');\n return { range: { [field]: { [rangeOp]: normalizedValue } } };\n }\n\n // Handle array operators\n if (this.isArrayOperator(operator)) {\n if (!Array.isArray(value)) {\n throw new Error(`Invalid array operator value: ${operator} requires an array value`);\n }\n const normalizedValues = this.normalizeArrayValues(value);\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n switch (operator) {\n case '$in':\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n case '$nin':\n // For empty arrays, return a query that matches everything\n if (normalizedValues.length === 0) {\n return { match_all: {} };\n }\n return {\n bool: {\n must_not: [{ terms: { [fieldWithKeyword]: normalizedValues } }],\n },\n };\n case '$all':\n // For empty arrays, return a query that will match nothing\n if (normalizedValues.length === 0) {\n return {\n bool: {\n must_not: [{ match_all: {} }],\n },\n };\n }\n return {\n bool: {\n must: normalizedValues.map(v => ({ term: { [fieldWithKeyword]: v } })),\n },\n };\n default:\n return { terms: { [fieldWithKeyword]: normalizedValues } };\n }\n }\n\n // Handle element operators\n if (this.isElementOperator(operator)) {\n switch (operator) {\n case '$exists':\n return value ? { exists: { field } } : { bool: { must_not: [{ exists: { field } }] } };\n default:\n return { exists: { field } };\n }\n }\n\n // Handle regex operators\n if (this.isRegexOperator(operator)) {\n return this.translateRegexOperator(field, value);\n }\n\n const fieldWithKeyword = this.addKeywordIfNeeded(field, value);\n return { term: { [fieldWithKeyword]: value } };\n }\n\n /**\n * Escapes wildcard metacharacters (* and ?) for use in wildcard queries.\n * Existing wildcard metacharacters in the pattern are escaped before\n * adding leading/trailing * to prevent semantic changes.\n * First escapes backslashes to avoid ambiguous encoding sequences.\n */\n private escapeWildcardMetacharacters(pattern: string): string {\n // First escape backslashes to avoid ambiguous encoding sequences\n // Then escape * and ? which are wildcard metacharacters\n return pattern.replace(/\\\\/g, '\\\\\\\\').replace(/\\*/g, '\\\\*').replace(/\\?/g, '\\\\?');\n }\n\n /**\n * Translates regex patterns to ElasticSearch query syntax\n */\n private translateRegexOperator(field: string, value: any): any {\n // Convert value to string if it's not already\n const regexValue = typeof value === 'string' ? value : value.toString();\n\n // Process regex pattern to handle anchors properly\n let processedRegex = regexValue;\n const hasStartAnchor = regexValue.startsWith('^');\n const hasEndAnchor = regexValue.endsWith('$');\n\n // If we have anchors, use wildcard query for better handling\n if (hasStartAnchor || hasEndAnchor) {\n // Remove anchors\n if (hasStartAnchor) {\n processedRegex = processedRegex.substring(1);\n }\n if (hasEndAnchor) {\n processedRegex = processedRegex.substring(0, processedRegex.length - 1);\n }\n\n // Escape existing wildcard metacharacters before adding leading/trailing *\n const escapedPattern = this.escapeWildcardMetacharacters(processedRegex);\n\n // Create wildcard pattern\n let wildcardPattern = escapedPattern;\n if (!hasStartAnchor) {\n wildcardPattern = '*' + wildcardPattern;\n }\n if (!hasEndAnchor) {\n wildcardPattern = wildcardPattern + '*';\n }\n\n return { wildcard: { [field]: wildcardPattern } };\n }\n\n // Use regexp for other regex patterns\n // Pass the original regex pattern through unchanged to preserve regex semantics\n // ElasticSearch regexp queries accept valid regex patterns directly\n return { regexp: { [field]: regexValue } };\n }\n\n private addKeywordIfNeeded(field: string, value: any): string {\n // Add .keyword suffix for string fields\n if (typeof value === 'string') {\n return `${field}.keyword`;\n }\n // Add .keyword suffix for string array fields\n if (Array.isArray(value) && value.every(item => typeof item === 'string')) {\n return `${field}.keyword`;\n }\n return field;\n }\n\n /**\n * Helper method to handle special cases for the $not operator\n */\n private handleNotOperatorSpecialCases(value: any, field: string): any | null {\n // For \"not null\", we need to use exists query\n if (value === null) {\n return { exists: { field } };\n }\n\n if (typeof value === 'object' && value !== null) {\n // For \"not {$eq: null}\", we need to use exists query\n if ('$eq' in value && value.$eq === null) {\n return { exists: { field } };\n }\n\n // For \"not {$ne: null}\", we need to use must_not exists query\n if ('$ne' in value && value.$ne === null) {\n return {\n bool: {\n must_not: [{ exists: { field } }],\n },\n };\n }\n }\n\n return null; // No special case applies\n }\n\n private translateOperator(operator: QueryOperator, value: any, field?: string): any {\n // Check if this is a valid operator\n if (!this.isOperator(operator)) {\n throw new Error(`Unsupported operator: ${operator}`);\n }\n\n // Special case for $not with null or $eq: null\n if (operator === '$not' && field) {\n const specialCaseResult = this.handleNotOperatorSpecialCases(value, field);\n if (specialCaseResult) {\n return specialCaseResult;\n }\n }\n\n // Handle logical operators\n if (this.isLogicalOperator(operator)) {\n // For $not operator with field context and nested operators, handle specially\n if (operator === '$not' && field && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const entries = Object.entries(value);\n\n // Handle multiple operators in $not\n if (entries.length > 0) {\n // If all entries are operators, handle them as a single condition\n if (entries.every(([op]) => this.isOperator(op))) {\n const translatedCondition = this.translateFieldConditions(field, value);\n return {\n bool: {\n must_not: [translatedCondition],\n },\n };\n }\n\n // Handle single nested operator\n if (entries.length === 1 && entries[0] && this.isOperator(entries[0][0])) {\n const [nestedOp, nestedVal] = entries[0] as [QueryOperator, any];\n const translatedNested = this.translateFieldOperator(field, nestedOp, nestedVal);\n return {\n bool: {\n must_not: [translatedNested],\n },\n };\n }\n }\n }\n return this.translateLogicalOperator(operator, value);\n }\n\n // If a field is provided, use translateFieldOperator for more specific translation\n if (field) {\n return this.translateFieldOperator(field, operator, value);\n }\n\n // For non-logical operators without a field context, just return the value\n // The actual translation happens in translateFieldConditions where we have the field context\n return value;\n }\n\n /**\n * Translates field conditions to ElasticSearch query syntax\n * Handles special cases like range queries and multiple operators\n */\n private translateFieldConditions(field: string, conditions: Record<string, any>): any {\n // Special case: Optimize multiple numeric operators into a single range query\n if (this.canOptimizeToRangeQuery(conditions)) {\n return this.createRangeQuery(field, conditions);\n }\n\n // Handle all other operators consistently\n const queryConditions: any[] = [];\n Object.entries(conditions).forEach(([operator, value]) => {\n if (this.isOperator(operator)) {\n queryConditions.push(this.translateOperator(operator as QueryOperator, value, field));\n } else {\n // Handle non-operator keys (should not happen in normal usage)\n const fieldWithKeyword = this.addKeywordIfNeeded(`${field}.${operator}`, value);\n queryConditions.push({ term: { [fieldWithKeyword]: value } });\n }\n });\n\n // Return single condition without wrapping\n if (queryConditions.length === 1) {\n return queryConditions[0];\n }\n\n // Combine multiple conditions with AND logic\n return {\n bool: {\n must: queryConditions,\n },\n };\n }\n\n /**\n * Checks if conditions can be optimized to a range query\n */\n private canOptimizeToRangeQuery(conditions: Record<string, any>): boolean {\n return Object.keys(conditions).every(op => this.isNumericOperator(op)) && Object.keys(conditions).length > 0;\n }\n\n /**\n * Creates a range query from numeric operators\n */\n private createRangeQuery(field: string, conditions: Record<string, any>): any {\n const rangeParams = Object.fromEntries(\n Object.entries(conditions).map(([op, val]) => [op.replace('$', ''), this.normalizeComparisonValue(val)]),\n );\n\n return { range: { [field]: rangeParams } };\n }\n}\n","import { Client as ElasticSearchClient } from '@elastic/elasticsearch';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport { createVectorErrorId } from '@mastra/core/storage';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n DeleteVectorsParams,\n} from '@mastra/core/vector';\nimport { MastraVector, validateUpsert, validateTopK } from '@mastra/core/vector';\nimport { ElasticSearchFilterTranslator } from './filter';\nimport type { ElasticSearchVectorFilter } from './filter';\n\nconst METRIC_MAPPING = {\n cosine: 'cosine',\n euclidean: 'l2_norm',\n dotproduct: 'dot_product',\n} as const;\n\nconst REVERSE_METRIC_MAPPING = {\n cosine: 'cosine',\n l2_norm: 'euclidean',\n dot_product: 'dotproduct',\n} as const;\n\ntype ElasticSearchVectorParams = QueryVectorParams<ElasticSearchVectorFilter>;\n\nexport class ElasticSearchVector extends MastraVector<ElasticSearchVectorFilter> {\n private client: ElasticSearchClient;\n\n /**\n * Creates a new ElasticSearchVector client.\n *\n * @param {string} url - The url of the ElasticSearch node.\n */\n constructor({ url, id }: { url: string } & { id: string }) {\n super({ id });\n this.client = new ElasticSearchClient({ node: url });\n }\n\n /**\n * Creates a new collection with the specified configuration.\n *\n * @param {string} indexName - The name of the collection to create.\n * @param {number} dimension - The dimension of the vectors to be stored in the collection.\n * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is created.\n */\n async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'INVALID_ARGS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Dimension must be a positive integer',\n details: { indexName, dimension },\n });\n }\n\n try {\n await this.client.indices.create({\n index: indexName,\n mappings: {\n properties: {\n metadata: { type: 'object' },\n id: { type: 'keyword' },\n embedding: {\n type: 'dense_vector',\n dims: dimension,\n index: true,\n similarity: METRIC_MAPPING[metric],\n },\n },\n },\n });\n } catch (error: any) {\n const message = error?.message || error?.toString();\n if (message && message.toLowerCase().includes('already exists')) {\n // Fetch collection info and check dimension\n await this.validateExistingIndex(indexName, dimension, metric);\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'CREATE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n }\n\n /**\n * Lists all indexes.\n *\n * @returns {Promise<string[]>} A promise that resolves to an array of indexes.\n */\n async listIndexes(): Promise<string[]> {\n try {\n const response = await this.client.cat.indices({ format: 'json' });\n const indexes = response\n .map((record: { index?: string }) => record.index)\n .filter((index: string | undefined): index is string => index !== undefined && !index.startsWith('.'));\n\n return indexes;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'LIST_INDEXES', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Validates that an existing index matches the requested dimension and metric.\n * Throws an error if there's a mismatch, otherwise allows idempotent creation.\n */\n protected async validateExistingIndex(indexName: string, dimension: number, metric: string): Promise<void> {\n let info: IndexStats;\n try {\n info = await this.describeIndex({ indexName });\n } catch (infoError) {\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'FETCH_FAILED'),\n text: `Index \"${indexName}\" already exists, but failed to fetch index info for dimension check.`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n details: { indexName },\n },\n infoError,\n );\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n\n const existingDim = info?.dimension;\n const existingMetric = info?.metric;\n\n if (existingDim === dimension) {\n this.logger?.info(\n `Index \"${indexName}\" already exists with ${existingDim} dimensions and metric ${existingMetric}, skipping creation.`,\n );\n if (existingMetric !== metric) {\n this.logger?.warn(\n `Attempted to create index with metric \"${metric}\", but index already exists with metric \"${existingMetric}\". To use a different metric, delete and recreate the index.`,\n );\n }\n } else if (info) {\n const mastraError = new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'VALIDATE_INDEX', 'DIMENSION_MISMATCH'),\n text: `Index \"${indexName}\" already exists with ${existingDim} dimensions, but ${dimension} dimensions were requested`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, existingDim, requestedDim: dimension },\n });\n this.logger?.trackException(mastraError);\n this.logger?.error(mastraError.toString());\n throw mastraError;\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n const indexInfo = await this.client.indices.get({ index: indexName });\n const mappings = indexInfo[indexName]?.mappings;\n const embedding: any = mappings?.properties?.embedding;\n const similarity = embedding.similarity as keyof typeof REVERSE_METRIC_MAPPING;\n\n const countInfo = await this.client.count({ index: indexName });\n\n return {\n dimension: Number(embedding.dims),\n count: Number(countInfo.count),\n metric: REVERSE_METRIC_MAPPING[similarity],\n };\n }\n\n /**\n * Deletes the specified index.\n *\n * @param {string} indexName - The name of the index to delete.\n * @returns {Promise<void>} A promise that resolves when the index is deleted.\n */\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n await this.client.indices.delete({ index: indexName });\n } catch (error: any) {\n // Check if error is \"index not found\" - allow idempotent delete\n const isIndexNotFound =\n error?.statusCode === 404 ||\n error?.body?.error?.type === 'index_not_found_exception' ||\n error?.meta?.statusCode === 404;\n\n if (isIndexNotFound) {\n // Silently return for idempotent delete behavior\n return;\n }\n\n // For all other errors, wrap, log, track, and rethrow\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_INDEX', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n throw mastraError;\n }\n }\n\n /**\n * Inserts or updates vectors in the specified collection.\n *\n * @param {string} indexName - The name of the collection to upsert into.\n * @param {number[][]} vectors - An array of vectors to upsert.\n * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.\n * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.\n * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.\n */\n async upsert({ indexName, vectors, metadata = [], ids }: UpsertVectorParams): Promise<string[]> {\n // Validate input parameters and vector values\n validateUpsert('ELASTICSEARCH', vectors, metadata, ids, true);\n\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const operations = [];\n\n try {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions(vectors, indexInfo.dimension);\n\n for (let i = 0; i < vectors.length; i++) {\n const operation = {\n index: {\n _index: indexName,\n _id: vectorIds[i],\n },\n };\n\n const document = {\n id: vectorIds[i],\n embedding: vectors[i],\n metadata: metadata[i] || {},\n };\n\n operations.push(operation);\n operations.push(document);\n }\n\n if (operations.length > 0) {\n const response = await this.client.bulk({ operations, refresh: true });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n // Operations alternate: operation, document, operation, document...\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const failedId = operationDoc?.index?._id || vectorIds[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i * 2;\n const operationDoc = operations[operationIndex] as { index?: { _id?: string } };\n const successId = operationDoc?.index?._id || vectorIds[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk upsert partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPSERT', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, vectorCount: vectors?.length || 0 },\n },\n error,\n );\n }\n }\n\n /**\n * Queries the specified collection using a vector and optional filter.\n *\n * @param {string} indexName - The name of the collection to query.\n * @param {number[]} queryVector - The vector to query with.\n * @param {number} [topK] - The maximum number of results to return.\n * @param {Record<string, any>} [filter] - An optional filter to apply to the query.\n * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.\n * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.\n */\n async query({\n indexName,\n queryVector,\n filter,\n topK = 10,\n includeVector = false,\n }: ElasticSearchVectorParams): Promise<QueryResult[]> {\n // Validate topK parameter\n validateTopK('ELASTICSEARCH', topK);\n\n try {\n const translatedFilter = this.transformFilter(filter);\n\n const response = await this.client.search({\n index: indexName,\n knn: {\n field: 'embedding',\n query_vector: queryVector,\n k: topK,\n num_candidates: topK * 2,\n ...(translatedFilter ? { filter: translatedFilter } : {}),\n },\n _source: ['id', 'metadata', 'embedding'],\n });\n\n const results = response.hits.hits.map((hit: any) => {\n const source = hit._source || {};\n return {\n id: String(source.id || ''),\n score: typeof hit._score === 'number' ? hit._score : 0,\n metadata: source.metadata || {},\n ...(includeVector && { vector: source.embedding as number[] }),\n };\n });\n\n return results;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'QUERY', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName, topK },\n },\n error,\n );\n }\n }\n\n /**\n * Validates the dimensions of the vectors.\n *\n * @param {number[][]} vectors - The vectors to validate.\n * @param {number} dimension - The dimension of the vectors.\n * @returns {void}\n */\n private validateVectorDimensions(vectors: number[][], dimension: number) {\n if (vectors.some(vector => vector.length !== dimension)) {\n throw new Error('Vector dimension does not match index dimension');\n }\n }\n\n /**\n * Transforms the filter to the ElasticSearch DSL.\n *\n * @param {ElasticSearchVectorFilter} filter - The filter to transform.\n * @returns {Record<string, any>} The transformed filter.\n */\n private transformFilter(filter?: ElasticSearchVectorFilter): any {\n const translator = new ElasticSearchFilterTranslator();\n return translator.translate(filter);\n }\n\n /**\n * Updates vectors by ID or filter with the provided vector and/or metadata.\n * @param params - Parameters containing either id or filter for targeting vectors to update\n * @param params.indexName - The name of the index containing the vector(s).\n * @param params.id - The ID of a single vector to update (mutually exclusive with filter).\n * @param params.filter - A filter to match multiple vectors to update (mutually exclusive with id).\n * @param params.update - An object containing the vector and/or metadata to update.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector(params: UpdateVectorParams<ElasticSearchVectorFilter>): Promise<void> {\n const { indexName, update } = params;\n\n // Validate mutually exclusive parameters\n if ('id' in params && 'filter' in params && params.id && params.filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'id and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!update.vector && !update.metadata) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_UPDATES'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'No updates provided',\n details: { indexName },\n });\n }\n\n // Validate empty filter\n if ('filter' in params && params.filter && Object.keys(params.filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot update with empty filter',\n details: { indexName },\n });\n }\n\n // Type-narrowing: check if updating by id or by filter\n if ('id' in params && params.id) {\n // Update by ID\n await this.updateVectorById(indexName, params.id, update);\n } else if ('filter' in params && params.filter) {\n // Update by filter\n await this.updateVectorsByFilter(indexName, params.filter, update);\n } else {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either id or filter must be provided',\n details: { indexName },\n });\n }\n }\n\n /**\n * Updates a single vector by its ID.\n */\n private async updateVectorById(\n indexName: string,\n id: string,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n let existingDoc;\n try {\n // First get the current document to merge with updates\n const result = await this.client\n .get({\n index: indexName,\n id: id,\n })\n .catch(() => {\n throw new Error(`Document with ID ${id} not found in index ${indexName}`);\n });\n\n if (!result || !result._source) {\n throw new Error(`Document with ID ${id} has no source data in index ${indexName}`);\n }\n existingDoc = result;\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n\n const source = existingDoc._source as any;\n const updatedDoc: Record<string, any> = {\n id: source?.id || id,\n };\n\n try {\n // Update vector if provided\n if (update.vector) {\n // Get index stats to check dimension\n const indexInfo = await this.describeIndex({ indexName });\n\n // Validate vector dimensions\n this.validateVectorDimensions([update.vector], indexInfo.dimension);\n\n updatedDoc.embedding = update.vector;\n } else if (source?.embedding) {\n updatedDoc.embedding = source.embedding;\n }\n\n // Update metadata if provided\n if (update.metadata) {\n updatedDoc.metadata = update.metadata;\n } else {\n updatedDoc.metadata = source?.metadata || {};\n }\n\n // Update the document\n await this.client.index({\n index: indexName,\n id: id,\n document: updatedDoc,\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n id,\n },\n },\n error,\n );\n }\n }\n\n /**\n * Updates multiple vectors matching a filter.\n */\n private async updateVectorsByFilter(\n indexName: string,\n filter: ElasticSearchVectorFilter,\n update: { vector?: number[]; metadata?: Record<string, any> },\n ): Promise<void> {\n try {\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n // Build the update script\n const scriptSource: string[] = [];\n const scriptParams: Record<string, any> = {};\n\n if (update.vector) {\n scriptSource.push('ctx._source.embedding = params.embedding');\n scriptParams.embedding = update.vector;\n }\n\n if (update.metadata) {\n scriptSource.push('ctx._source.metadata = params.metadata');\n scriptParams.metadata = update.metadata;\n }\n\n // Use update_by_query to update all matching documents\n await this.client.updateByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n script: {\n source: scriptSource.join('; '),\n params: scriptParams,\n lang: 'painless',\n },\n refresh: true,\n });\n } catch (error) {\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'UPDATE_VECTOR_BY_FILTER', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n filter: JSON.stringify(filter),\n },\n },\n error,\n );\n }\n }\n\n /**\n * Deletes a vector by its ID.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to delete.\n * @returns A promise that resolves when the deletion is complete.\n * @throws Will throw an error if the deletion operation fails.\n */\n async deleteVector({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n await this.client.delete({\n index: indexName,\n id: id,\n refresh: true,\n });\n } catch (error: unknown) {\n // Don't throw error if document doesn't exist (404)\n if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 404) {\n return;\n }\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTOR', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(id && { id }),\n },\n },\n error,\n );\n }\n }\n\n async deleteVectors({ indexName, filter, ids }: DeleteVectorsParams<ElasticSearchVectorFilter>): Promise<void> {\n // Validate mutually exclusive parameters\n if (ids && filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'MUTUALLY_EXCLUSIVE'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'ids and filter are mutually exclusive',\n details: { indexName },\n });\n }\n\n if (!ids && !filter) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'NO_TARGET'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Either filter or ids must be provided',\n details: { indexName },\n });\n }\n\n // Validate non-empty arrays and objects\n if (ids && ids.length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_IDS'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty ids array',\n details: { indexName },\n });\n }\n\n if (filter && Object.keys(filter).length === 0) {\n throw new MastraError({\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'EMPTY_FILTER'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n text: 'Cannot delete with empty filter',\n details: { indexName },\n });\n }\n\n try {\n if (ids) {\n // Delete by IDs using bulk API\n const bulkBody = ids.flatMap(id => [{ delete: { _index: indexName, _id: id } }]);\n\n const response = await this.client.bulk({\n operations: bulkBody,\n refresh: true,\n });\n\n // Check for item-level errors in bulk response\n if (response.errors) {\n const failedItems: Array<{ id: string; status: number; error: any }> = [];\n const successfulIds: string[] = [];\n\n // Iterate through items to collect failures\n for (let i = 0; i < response.items.length; i++) {\n const item = response.items[i];\n if (!item) continue;\n const operationType = Object.keys(item)[0] as 'index' | 'create' | 'update' | 'delete';\n const operationResult = item[operationType];\n if (!operationResult) continue;\n\n if (operationResult.error) {\n // Extract the ID from the original operations array\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const failedId = operationDoc?.delete?._id || ids[i] || `unknown-${i}`;\n\n failedItems.push({\n id: failedId,\n status: operationResult.status || 0,\n error: operationResult.error,\n });\n } else if (operationResult?.status && operationResult.status < 300) {\n // Success - extract ID\n const operationIndex = i;\n const operationDoc = bulkBody[operationIndex] as { delete?: { _id?: string } };\n const successId = operationDoc?.delete?._id || ids[i];\n if (successId) {\n successfulIds.push(successId);\n }\n }\n }\n\n // If there are failures, log and throw error\n if (failedItems.length > 0) {\n const failedItemDetails = failedItems\n .map(item => `${item.id}: ${item.error?.reason || item.error?.type || JSON.stringify(item.error)}`)\n .join('; ');\n\n const mastraError = new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'BULK_PARTIAL_FAILURE'),\n text: `Bulk delete partially failed: ${failedItems.length} of ${response.items.length} operations failed. Failed items: ${failedItemDetails}`,\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n totalOperations: response.items.length,\n failedCount: failedItems.length,\n successfulCount: successfulIds.length,\n failedItemIds: failedItems.map(item => item.id).join(','),\n failedItemErrors: failedItemDetails,\n },\n },\n new Error(`Bulk delete operation had ${failedItems.length} failures`),\n );\n\n this.logger?.error(mastraError.toString());\n this.logger?.trackException(mastraError);\n\n // Throw error with details about failures\n throw mastraError;\n }\n }\n } else if (filter) {\n // Delete by filter using delete_by_query\n const translator = new ElasticSearchFilterTranslator();\n const translatedFilter = translator.translate(filter);\n\n await this.client.deleteByQuery({\n index: indexName,\n query: (translatedFilter as any) || { match_all: {} },\n refresh: true,\n });\n }\n } catch (error) {\n if (error instanceof MastraError) throw error;\n throw new MastraError(\n {\n id: createVectorErrorId('ELASTICSEARCH', 'DELETE_VECTORS', 'FAILED'),\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n indexName,\n ...(filter && { filter: JSON.stringify(filter) }),\n ...(ids && { idsCount: ids.length }),\n },\n },\n error,\n );\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/elasticsearch",
3
- "version": "1.0.0-beta.4",
3
+ "version": "1.0.0",
4
4
  "description": "ElasticSearch vector store provider for Mastra",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -29,10 +29,10 @@
29
29
  "tsup": "^8.5.0",
30
30
  "typescript": "^5.9.3",
31
31
  "vitest": "4.0.16",
32
- "@internal/lint": "0.0.53",
33
- "@internal/types-builder": "0.0.28",
34
- "@internal/storage-test-utils": "0.0.49",
35
- "@mastra/core": "1.0.0-beta.20"
32
+ "@internal/types-builder": "0.0.29",
33
+ "@internal/storage-test-utils": "0.0.50",
34
+ "@mastra/core": "1.0.0",
35
+ "@internal/lint": "0.0.54"
36
36
  },
37
37
  "peerDependencies": {
38
38
  "@mastra/core": ">=1.0.0-0 <2.0.0-0"