<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title><![CDATA[Enrico Zimuel - Elasticsearch Labs]]></title>
    <description><![CDATA[Articles and tutorials from the Search team at Elastic]]></description>
    <copyright><![CDATA[© 2026. Elasticsearch B.V. All Rights Reserved]]></copyright>
    <image>
      <title><![CDATA[Enrico Zimuel - Elasticsearch Labs]]></title>
      <url>https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt1121c0bf0e8a6e65/6a88da6340a1841030ef456f/search-labs-thumbnail.png</url>
      <link>https://www.elastic.co/cn/search-labs/author/enrico-zimuel</link>
    </image>
    <link>https://www.elastic.co/cn/search-labs/author/enrico-zimuel</link>
    <atom:link href="https://www.elastic.co/cn/search-labs/rss/author/enrico-zimuel.xml" rel="self" type="application/rss+xml"/>
    <language><![CDATA[cn]]></language>
    <lastBuildDate>Tue, 22 Sep 2026 03:47:15 GMT</lastBuildDate>
  <item>
    <title><![CDATA[如何使用 Mastra 和 Elasticsearch 构建代理式 AI 应用程序]]></title>
    <description><![CDATA[通过一个实际示例，了解如何使用 Mastra 和 Elasticsearch 构建智能体 AI 应用。]]></description>
    <content:encoded><![CDATA[<p>在本文中，我们将介绍如何使用 <a href="https://mastra.ai/">Mastra</a> TypeScript 框架来构建与 <a href="https://www.elastic.co/elasticsearch">Elasticsearch</a> 交互的智能体应用。</p><p>我们最近通过添加对 Elasticsearch 作为向量数据库的支持，参与了 <a href="https://github.com/mastra-ai/mastra">mastra-ai/mastra</a> 开源项目。借助这项新功能，您可以在 Mastra 中原生使用 Elasticsearch 来存储嵌入内容。除了向量之外，Elasticsearch 还提供了一系列高级功能，以满足您所有的上下文工程需求。(例如<a href="https://www.elastic.co/search-labs/blog/context-engineering-hybrid-search-evolution-agentic-ai">混合搜索和重排序</a>).</p><p>本文详细介绍了使用 Elasticsearch 实现检索增强生成 (RAG) 架构的智能体的创建过程。我们将展示一个演示项目，其中采用智能体方法来与存储在 Elasticsearch 中的科幻电影数据语料库进行交互。该项目可在 <a href="https://github.com/elastic/mastra-elasticsearch-example">elastic/mastra-elasticsearch-example</a> 获取。</p><h2>Mastra</h2><p>Mastra 是一个用于创建智能体 AI 应用的 TypeScript 框架。</p><p>Mastra的项目结构如下：</p>src/
├── mastra/
│   ├── agents/
│   │   └── weather-agent.ts
│   ├── tools/
│   │   └── weather-tool.ts
│   ├── workflows/
│   │   └── weather-workflow.ts
│   ├── scorers/
│   │   └── weather-scorer.ts
│   └── index.ts
├── .env.example
├── package.json
└── tsconfig.json<p>在 Mastra 中，您可以构建<a href="https://mastra.ai/docs/agents/overview">智能体</a>、<a href="https://mastra.ai/docs/agents/using-tools">工具</a>、<a href="https://mastra.ai/docs/workflows/overview">工作流</a>和<a href="https://mastra.ai/docs/evals/overview">评分</a>。</p><p><strong>智能体</strong>是一个接收消息作为输入并产生响应作为输出的类。智能体可以使用工具、大型语言模型 (LLM) 和内存（图 1）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt0f7484f7501997dc/6a170417cdacbffb5a7d28f6/f6aca2dcc7fcc45d25e06681649be1b2b7eb6781-706x721.png" alt="Mastra 中智能体工作原理示意图。" /><p>智能体的<strong>工具</strong>允许其与“外部世界”交互，例如与 Web API 通信或执行内部操作，如查询 Elasticsearch。<strong>内存</strong>组件对于存储对话历史（包括过去的输入和输出）至关重要。这些存储的上下文使智能体能够利用过去的交互，为未来的问题提供更知情且更相关的响应。</p><p><strong>工作流</strong>允许您使用清晰、结构化的步骤来定义复杂的任务序列，而不是依赖单个智能体的推理（图 2）。它们让您可以完全控制任务的分解方式、数据在任务之间的移动方式以及何时执行哪些任务。工作流默认使用内置执行引擎运行，也可以部署到<a href="https://mastra.ai/docs/deployment/workflow-runners">工作流运行器</a>。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltd82ea661569e1018/6a170419dc55de3adde00cc9/0dce161cf7891207015dc87532b5b90df1822432-880x252.png" alt="Mastra 中的工作流示例。" /><p>在 Mastra 中，您还可以定义分数，这些分数是通过模型评分、基于规则和统计方法来评估智能体输出的自动化测试结果。评分器返回<em>分数</em>：量化输出满足评估标准程度的数值（通常在 0 到 1 之间）。这些分数使您能够客观地跟踪性能、比较不同方法并识别 AI 系统中的改进领域。您可以使用自己的提示和评分函数自定义评分器。</p><h2>Elasticsearch</h2><p>要运行演示项目，我们需要一个正在运行的 Elasticsearch 实例。您可以在 <a href="https://www.elastic.co/cloud">Elastic Cloud</a> 上激活免费试用版，或使用 <a href="https://github.com/elastic/start-local"><code>start-local</code></a> 脚本在本地安装：</p>curl -fsSL https://elastic.co/start-local | sh<p>这将在您的计算机上安装 Elasticsearch 和 Kibana，并生成一个用于配置 Mastra 集成的 API 密钥。</p><p>API 密钥将显示为上一条命令的输出，并存储在 elastic-start-local 文件夹中的 <strong>.env</strong> 文件内。</p><h2>安装与配置演示</h2><p>我们创建了一个 <a href="https://github.com/elastic/mastra-elasticsearch-example">elastic/mastra-elasticsearch-example</a> 存储库，其中包含演示项目的源代码。存储库中报告的示例演示了如何在 Mastra 中创建一个实现 RAG 架构、用于从 Elasticsearch 检索文档的智能体。</p><p>我们为演示提供了一个关于科幻电影的数据集。我们从 <a href="https://www.kaggle.com/datasets/rajugc/imdb-movies-dataset-based-on-genre/versions/2?select=scifi.csv">Kaggle</a> 上的 IMDb 数据集中提取了 500 部电影。</p><p>第一步是使用 npm 安装项目依赖，执行以下命令：</p>npm install<p>然后我们需要配置包含各项设置的 <strong>.env</strong> 文件。我们可以使用以下命令，复制 <strong>.env.example</strong> 文件的结构来生成该文件：</p>cp .env.example .env<p>现在我们可以编辑 .env 文件，补充缺失的信息：</p>OPENAI_API_KEY=
ELASTICSEARCH_URL=
ELASTICSEARCH_API_KEY=
ELASTICSEARCH_INDEX_NAME=scifi-movies<p>Elasticsearch 索引的名称为 <strong><code>scifi-movies</code></strong>。如果您想更改它，可以使用环境变量 <code>ELASTICSEARCH_INDEX_NAME</code>。</p><p>我们使用 OpenAI 作为嵌入服务，这意味着您需要在 <code>OPENAI_API_KEY</code> 环境变量中提供 OpenAI 的 API 密钥。</p><p>示例中使用的嵌入模型是 <a href="https://developers.openai.com/api/docs/models/text-embedding-3-small">openai/text-embedding-3-small</a>，嵌入维度为 1536。</p><p>为了生成最终答案，我们使用了 <a href="https://developers.openai.com/api/docs/models/gpt-5-nano">openai/gpt-5-nano</a> 模型来降低成本。</p><p>RAG 架构允许您使用性能较低（且通常成本较低）的 LLM 模型，因为答案落地的主要工作是由检索组件（此处为 Elasticsearch）承担。</p><p>较小的 LLM 仅负责两个主要任务：</p><ul><li><p><strong>重写/嵌入查询：</strong>将用户的自然语言问题转换为用于语义搜索的向量嵌入。</p></li><li><p><strong>综合答案：</strong>获取高度相关的检索上下文块（文档/电影），并将它们合成为一个连贯的、最终的、人类可读的答案，并遵循给出的提示指示。</p></li></ul><p>由于 RAG 流程可<strong>提供答案所需的精确事实上下文</strong>，最终的 LLM 不需要非常庞大或高度复杂，也不需要在其自身参数中拥有所有必需的知识（这正是大型、昂贵模型的优势所在）。它本质上是一个针对 Elasticsearch 提供的上下文的高级文本摘要器和格式化器，而不是一个功能齐全的知识库本身。这使得可以使用像 <code>gpt-5-nano</code> 等模型来优化成本和延迟。</p><p>配置完 .env 文件后，可以使用以下命令将电影数据导入 Elasticsearch：</p>npx tsx src/utility/store.ts<p>您应该看到如下输出：</p>🚀 Starting ingestion of 500 movies from 500_scifi_movies.jsonl...
Ingesting ░░░░░░░░░░░░░░░░░░░░░░░░ 1/500 (0%) | ok:1 | fail:0 | chunks:1 | eta:19m 33s | current:Capricorn One
Ingesting ░░░░░░░░░░░░░░░░░░░░░░░░ 2/500 (0%) | ok:2 | fail:0 | chunks:2 | eta:10m 32s | current:Doghouse
Ingesting ░░░░░░░░░░░░░░░░░░░░░░░░ 3/500 (1%) | ok:3 | fail:0 | chunks:3 | eta:7m 33s | current:Dinocroc
Ingesting ░░░░░░░░░░░░░░░░░░░░░░░░ 4/500 (1%) | ok:4 | fail:0 | chunks:7 | eta:6m 10s | current:Back to the Future           
Ingesting ░░░░░░░░░░░░░░░░░░░░░░░░ 5/500 (1%) | ok:5 | fail:0 | chunks:9 | eta:5m 14s | current:The Projected Man            
Ingesting ░░░░░░░░░░░░░░░░░░░░░░░░ 6/500 (1%) | ok:6 | fail:0 | chunks:11 | eta:4m 41s | current:I, Robot
...
✅ Ingestion complete in 1m 46s. Success: 500, Failed: 0, Chunks: 693.<p>scifi-movies 索引的映射包含以下字段：</p><ul><li><p><strong>embedding</strong>：dense_vector，1536 维，cosine 相似度。</p></li><li><p><strong>description</strong>，包含电影描述的文本。</p></li><li><p><strong>director</strong>，包含导演姓名的文本。</p></li><li><p><strong>title</strong>，包含电影标题的文本。</p></li></ul><p>我们使用 title + description 生成嵌入向量。由于 title 和 description 是两个独立的字段，将两者拼接可以确保生成的嵌入向量同时捕获电影的具体唯一标识 (title) 和丰富的描述性上下文 (description)，从而实现更准确、更全面的语义搜索结果。这种组合输入为嵌入模型提供了更好的文档内容单一表示，便于相似性匹配。</p><h2>运行演示</h2><p>您可以使用以下命令运行演示：</p>npm run dev<p>该命令将在 <strong>localhost:4111</strong> 启动一个 Web 应用，以访问 Mastra Studio（图3）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt8a539df677a33b36/6a17041a47d49c36842d88a0/1567e309df21a12bcf1dfef4429f82342549956c-1705x1079.png" alt="Mastra Studio 的屏幕截图，其中包含 Elasticsearch Agent 示例。" /><p><a href="https://mastra.ai/docs/getting-started/studio">Mastra Studio</a>提供了一个交互式 UI 用于构建和测试您的智能体，以及一个将 Mastra 应用程序作为本地服务公开的 REST API。这让您可以立即开始构建，无需担心集成问题。</p><p>我们提供了一个 <strong>Elasticsearch Agent</strong>，它使用 Mastra 的 <a href="https://mastra.ai/reference/tools/vector-query-tool">createVectorQueryTool</a> 作为工具，利用 Elasticsearch 执行语义搜索。该智能体采用 RAG 方法搜索相关文档（即电影）来回答用户的问题。</p><p>该智能体使用以下提示：</p>You are a helpful assistant that answers questions based on the provided context.
Follow these steps for each response:

1. First, carefully analyze the retrieved context chunks and identify key information.
2. Break down your thinking process about how the retrieved information relates to the query.
3. Draw conclusions based only on the evidence in the retrieved context.
4. If the retrieved chunks don't contain enough information, explicitly state what's missing.

Format your response as:
THOUGHT PROCESS:
- Step 1: [Initial analysis of retrieved chunks]
- Step 2: [Reasoning based on chunks]

FINAL ANSWER:
[Your concise answer based on the retrieved context]

Important: When asked to answer a question, please base your answer only on the context provided in the tool. 
If the context doesn't contain enough information to fully answer the question, please state that explicitly and stop it.
Do not add more information than what is present in the retrieved chunks.
Remember: Explain how you're using the retrieved information to reach your conclusions.<p>如果您点击 <code>Mastra Studio &gt; Agents</code>菜单并选择 <strong>Elasticsearch Agent</strong>，则可以使用聊天系统测试该智能体。例如，您可以提出如下关于科幻电影的问题：</p><p><em>查找五部关于 UFO 的电影或电视剧</em>。</p><p>您会注意到智能体将执行 vectorQueryTool。您可以点击调用的工具来查看输入和输出。执行结束时，LLM 将根据来自 Elasticsearch 的 scifi-movies 索引的上下文回答您的问题（图 4）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltda92a9b6e56528d3/6a17041c2b835f9724f4b0d6/d9998d4f687984de98845dae52d1288166abf448-1344x1071.png" alt=" 使用 Elasticsearch 智能体的 LLM 响应。" /><p>Mastra 在内部执行以下步骤：</p><ol><li><p><strong>向量转换：</strong>用户的问题 “<em>查找五部关于 UFO 的电影或电视剧</em>” 使用 OpenAI 的 <code>openai/text-embedding-3-small</code> 模型转换为向量嵌入。</p></li><li><p><strong>向量搜索：</strong>然后将此嵌入向量用于通过向量搜索查询 Elasticsearch。</p></li><li><p><strong>结果检索：</strong>Elasticsearch 返回一组与查询高度相关的 10 部电影（即那些向量与用户查询向量最接近的电影）。</p></li><li><p><strong>答案生成：</strong>检索到的电影和原始用户问题被发送给 LLM，具体为 <code>openai/gpt-5-nano</code>。LLM 处理这些信息并生成最终答案，确保满足用户请求的五个结果。</p></li></ol><h2>Elasticsearch 智能体</h2><p>下面我们展示了 Elasticsearch 智能体的源代码。</p>import { Agent } from "@mastra/core/agent";
import { ElasticSearchVector } from '@mastra/elasticsearch';
import { createVectorQueryTool } from '@mastra/rag';
import { ModelRouterEmbeddingModel } from "@mastra/core/llm";
import { Memory } from "@mastra/memory";

const es_url = process.env.ELASTICSEARCH_URL;
const es_apikey = process.env.ELASTICSEARCH_API_KEY;
const es_index_name = process.env.ELASTICSEARCH_INDEX_NAME;
const prompt = 'insert here the previous prompt';

const esVector = new ElasticSearchVector({
  id: 'elasticsearch-vector',
  url: es_url,
  auth: {
    apiKey : es_apikey
  }
});

const vectorQueryTool = createVectorQueryTool({
  vectorStore: esVector,
  indexName: es_index_name,
  model: new ModelRouterEmbeddingModel("openai/text-embedding-3-small")
});

export const elasticsearchAgent = new Agent({
  id: "elasticsearch-agent",
  name: "Elasticsearch Agent",
  instructions: prompt,
  model: 'openai/gpt-5-nano',
  tools: { vectorQueryTool },
  memory: new Memory(),
});<p><strong>vectorQueryTool</strong> 是被调用来实现 RAG 示例中检索部分的工具。它使用了 <a href="https://mastra.ai/reference/vectors/elasticsearch">Elastic 为 Mastra 贡献的 ElasticSearchVector</a> 实现。</p><p>该智能体是 agent 类的一个对象，它使用了 vectorQueryTool、提示和内存组件。可以看出，将 Elasticsearch 连接到智能体所需的代码量非常少。</p><h2>结论</h2><p>本文展示了将 Elasticsearch 与 Mastra 框架集成以构建复杂的智能体 AI 应用程序的简便性和强大功能。具体来说，我们逐步实现了一个 RAG 智能体，能够对 Elasticsearch 中索引的科幻电影数据语料库执行语义搜索。</p><p>一个关键收获是 Elastic 对 Mastra 开源项目的直接贡献，提供了 Elasticsearch 作为向量存储的原生支持。这种集成显著降低了入门门槛，正如 <strong>Elasticsearch Agent</strong> 源代码所证明的那样。使用 <code>ElasticSearchVector</code> 和 <code>createVectorQueryTool</code>，将 Elasticsearch 连接到智能体的完整设置仅需最少数量的配置代码行。</p><p>Elasticsearch 提供了多项高级功能来增强结果相关性。例如，<a href="https://www.elastic.co/elasticsearch/hybrid-search">混合搜索</a>通过将词法搜索与向量搜索相结合，显著提高了准确性。另一个有趣的功能是在混合搜索结束时使用最新的<a href="https://www.elastic.co/search-labs/tutorials/jina-tutorial/jina-reranker-v3">Jina 模型</a>重排序。要了解有关这些技术的更多信息，请参阅 Elasticsearch Labs 的以下文章：</p><ul><li><p><a href="https://www.elastic.co/search-labs/blog/hybrid-search-elasticsearch">Elasticsearch 混合搜索</a> - Valentin Crettaz</p></li><li><p><a href="https://www.elastic.co/search-labs/blog/jina-models-elasticsearch-guide">Jina 模型介绍、功能及其在 Elasticsearch 中的应用</a> 作者：Scott Martens</p></li></ul><p>我们还鼓励您探索所提供的示例，并开始使用 Mastra 和 Elasticsearch 构建自己的数据驱动的智能体应用。如需了解更多关于 Mastra 的信息，您可在<a href="https://mastra.ai/docs">此处</a>查看官方文档。</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/build-agentic-ai-applications-mastra-elasticsearch</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/build-agentic-ai-applications-mastra-elasticsearch</guid>
    <category><![CDATA[智能体 AI]]></category>
    <dc:creator><![CDATA[Enrico Zimuel]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt083181bab7c0e2d0/6a17041eacf0880b70be99f5/ab30baf2f908534840c5d71a46705773807baf54-1280x720.png" length="0" type="image/png"/>
    <pubDate>Wed, 08 Apr 2026 00:00:00 GMT</pubDate>
  </item>
  <item>
    <title><![CDATA[适用 Elasticsearch 的 Gemini CLI 扩展及工具和技能]]></title>
    <description><![CDATA[Elastic 推出了适用于谷歌 Gemini CLI 的扩展，用于在开发人员和智能体工作流中搜索、检索和分析 Elasticsearch 数据。
]]></description>
    <content:encoded><![CDATA[<p>我们很高兴地宣布， Elastic 发布了适用于 Google 的 Gemini CLI 扩展，将 <a href="https://www.elastic.co/elasticsearch">Elasticsearch</a> 和 <a href="https://www.elastic.co/elasticsearch/agent-builder">Elastic Agent Builder</a> 的全部功能直接引入您的 AI 开发工作流。此扩展还提供几种最近开发的智能体技能，用于与 Elasticsearch 交互。</p><p>该扩展以开源项目的形式在<a href="https://github.com/elastic/gemini-cli-elasticsearch">此处</a>提供。</p><h2>Gemini CLI 是什么？如何安装？</h2><p><a href="https://geminicli.com/">Gemini CLI</a> 是一个开源的 AI 智能体，它可将 Google 的 Gemini 模型直接引入命令行。它允许开发人员从终端与 AI 进行交互，以执行诸如生成代码、编辑文件、运行 shell 命令和从网上检索信息等任务。</p><p>与典型的聊天界面不同，Gemini CLI 可与您的本地开发环境集成，这意味着它可以直接在终端内理解项目上下文、修改文件、运行构建或测试，以及自动化工作流。这对于想要在不离开命令行工作流的情况下进行 AI 辅助编码和自动化的开发人员、网站可靠性工程师 (SREs) 和工程师来说非常有用。</p><p>Gemini CLI 可通过多个软件包管理器安装。最常用的方法是通过 npm 安装：</p>npm install -g @google/gemini-cli<p>如要了解其他安装选项，请参阅<a href="https://geminicli.com/docs/get-started/installation/">官方安装页面</a>。</p><p>安装完成后，运行以下命令启动 CLI：</p>gemini<p>您会看到一个屏幕，如图 1 所示：</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt4ff43abe550941b4/6a17072ba29299fc2ad00fa4/6dfcec4a77b3dc83bf0d974417bf2e211abb1f4f-876x468.png" alt="Gemini CLI 的屏幕截图。" /><h2>配置 Elasticsearch</h2><p>我们需要运行一个 Elasticsearch 实例。如要使用模型上下文协议 (MCP) 服务器，您还需要安装 Kibana 9.3+。如要使用下面描述的 Elasticsearch 查询语言 (ES|QL) 技能 (<code>esql</code>)，则不需要 Kibana。</p><p>您可以在 <a href="https://www.elastic.co/cloud">Elastic Cloud</a> 上激活免费试用版，或使用 <a href="https://github.com/elastic/start-local"><code>start-local</code></a> 脚本在本地安装：</p>curl -fsSL https://elastic.co/start-local | sh<p>这将在您的计算机上安装 Elasticsearch 和 Kibana，并生成一个用于配置 Gemini CLI 的 API 密钥。</p><p>API 密钥将显示为上一条命令的输出，并存储在 <strong>.env</strong> 文件中，该文件位于 <strong><code>elastic-start-local</code></strong> 文件夹。</p><p>如果您使用的是本地部署的 Elasticsearch（例如使用 <code>start-local</code>），并且您想将 Elastic Agent Builder 与 MCP 一起使用，那么您还需要连接一个大型语言模型 (LLM)。您可以阅读<a href="https://www.elastic.co/docs/explore-analyze/ai-features/llm-guides/llm-connectors">此文档页面</a>以了解不同的选项。</p><p>如果您使用的是 Elastic Cloud（或无服务器架构），那么您已经预先建立了 LLM 连接。</p><h2>安装 Elasticsearch 扩展</h2><p>您可以使用以下命令为 Gemini CLI 安装 Elasticsearch 扩展：</p>gemini extensions install https://github.com/elastic/gemini-cli-elasticsearch<p>您可以通过打开 Gemini 并执行以下命令来检查扩展程序是否已成功安装：</p>/extensions list<p>您应该看到 Elasticsearch 扩展可用。</p><p>如要使用 MCP 集成，您需要安装 Elasticsearch 9.3 或更高版本。您需要从 <a href="https://www.elastic.co/kibana">Kibana</a> 获取您的 MCP 服务器 URL：</p><ul><li><p>从智能体处获取 MCP 服务器 URL &gt; 查看所有工具 &gt; 管理 MCP &gt; 复制 MCP 服务器 URL。</p></li><li><p>URL 将如下所示：https://your-kibana-instance/api/agent_builder/mcp</p></li></ul><p>您需要 Elasticsearch 终端 URL。这通常显示在 Kibana Elasticsearch 页面的顶部。如果您使用 <code>start-local</code> 运行 Elasticsearch，那么您已经在 <code>start-local</code>.env 文件的<code>ES_LOCAL_URL</code> 密钥中拥有了终端。</p><p>您还需要一个 API 密钥。如果您使用 <code>start-local</code> 运行 Elasticsearch，那么您已经在 <code>start-local</code> .env 文件中拥有了 <code>ES_LOCAL_API_KEY</code>。否则，您可以使用 Kibana 界面创建 API 密钥，详见<a href="https://www.elastic.co/docs/deploy-manage/api-keys/elasticsearch-api-keys">此处</a>：</p><ul><li><p>在 Kibana 中：Stack Management &gt; Security &gt; API 密钥 &gt; 创建 API 密钥。</p></li><li><p>我们建议仅设置 API 密钥的读取权限，并启用 <code>feature_agentBuilder.read</code> 权限，详见<a href="https://www.elastic.co/docs/explore-analyze/ai-features/agent-builder/permissions#grant-access-with-roles">此处</a>。</p></li><li><p>复制已编码的 API 密钥值。</p></li></ul><p>在您的 shell 中设置所需的环境变量：</p>export ELASTIC_URL="your-elasticsearch-url"
export ELASTIC_MCP_URL="your-elasticsearch-mcp-url"
export ELASTIC_API_KEY="your-encoded-api-key"<h2>安装示例数据集</h2><p>您可以安装 Kibana 提供的<strong>电子商务订单</strong>数据集。它包含一个名为 <strong><code>kibana_sample_data_ecommerce</code></strong> 的单个索引，其中包含来自一家电子商务网站的 4675 个订单的信息。对于每笔订单，我们都有以下信息：</p><ul><li><p>客户信息（姓名、ID 号码、出生日期、电子邮件等）。</p></li><li><p>订单日期。</p></li><li><p>订单编号。</p></li><li><p>产品（包含价格、数量、ID、类别、折扣和其他详情的所有产品列表）</p></li><li><p>SKU。</p></li><li><p>总价（不含税，含税）。</p></li><li><p>总数量。</p></li><li><p>地理信息（城市、国家、洲、位置、地区）。</p></li></ul><p>如要安装示例数据，请在 Kibana 中打开<strong>集成</strong>页面（在顶部搜索栏中搜索“集成”），然后安装<strong>示例数据</strong>。更多详情请参阅<a href="https://www.elastic.co/docs/explore-analyze/#gs-get-data-into-kibana">此处</a>的文档。</p><p>本文旨在展示如何轻松配置 Gemini CLI 以连接到 Elasticsearch 并与 <strong><code>kibana_sample_data_ecommerce</code></strong> 索引交互。</p><h2>如何使用 Elasticsearch MCP（模型上下文协议）</h2><p>您可以在 Gemini 中使用以下命令检查连接：</p>/mcp list<p>您应该会看到 <strong><code>elastic-agent-builder</code></strong> 已启用，如图 2 所示：</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt52b85e7255360f3b/6a17072da929cf33d3ae08f5/1508423bc1d1bc3c04a1cb01e2d59495a3516ed1-1465x844.png" alt="`elastic-agent-builder` MCP 服务器及其工具列表。" /><p>Elasticsearch 提供了一组默认工具。请参阅<a href="https://www.elastic.co/docs/explore-analyze/ai-features/agent-builder/tools/builtin-tools-reference">此处</a>的描述。</p><p>使用这些工具，您可以与 Elasticsearch 进行交互，提出类似以下的问题：</p><ul><li><p><code>Give me the list of all the indexes available in Elasticsearch.</code></p></li><li><p><code>How many customers are based in the USA in the kibana_sample_data_ecommerce index of Elasticsearch?</code></p></li></ul><p>根据问题的不同，Gemini 会使用一个或多个可用工具来尝试回答问题。</p><h2>/elastic 命令</h2><p>在 Gemini CLI 的 Elasticsearch 扩展中，我们还添加了<strong><code>/elastic</code></strong> 命令。</p><p>如果执行 <strong><code>/help</code></strong> 命令，您将看到所有可用的 <code>/elastic</code> 选项（图 3）：</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt741c7451ecab10d2/6a17072ea6c2b9ccd6e79643/5b2a0727ce7a04354878dd048253d3f4d062324b-1983x230.png" alt="可用的 `/elastic` 命令。" /><p>这些命令在您想直接执行 <code>elastic-agent-builder</code> MCP 服务器的特定工具时会很有用。例如，使用以下命令可以获取 <code>kibana_sample_data_ecommerce</code> 的映射：</p>/elastic:get-mapping kibana_sample_data_ecommerce<p>这些命令本质上是执行特定工具的快捷方式，而不是依赖 Gemini 模型来确定应该调用哪个工具。</p><h2>如何使用 Elasticsearch 的技能？</h2><p>该扩展还附带了 ES|QL 的<a href="https://github.com/elastic/gemini-cli-elasticsearch/tree/main/skills/esql">代理技能，ES|QL</a> 是 Elasticsearch 中提供的 <a href="https://www.elastic.co/docs/explore-analyze/discover/try-esql">Elasticsearch 查询语言</a>。<a href="https://agentskills.io/home">Agent Skills</a> 是一种开放格式，为 AI 编码智能体（如 Gemini CLI）提供特定任务的自定义指令。它们使用一种称为<em>渐进式披露</em>的概念，即在系统初始提示中只添加对技能的简要说明。当您要求智能体执行任务时，比如查询 Elasticsearch，它会将请求与相关技能匹配，并动态加载详细说明。这是一种高效管理词元预算的方法，同时为 AI 提供所需的准确上下文。</p><p><strong><code>esql</code></strong><strong>技能</strong>旨在让 Gemini CLI 直接针对集群编写和执行 ES|QL 查询。ES|QL 是一种功能强大的管道化查询语言，能非常直观地进行数据探索、日志分析和聚合。启用该技能后，您无需查找 ES|QL 语法；只需用自然语言向 Gemini CLI 提出有关数据的问题，智能体会处理剩下的问题。</p><p>执行操作是通过在终端中运行简单的 <a href="https://curl.se/">curl</a> 命令来完成的。之所以能做到这一点，是因为 Elasticsearch 提供了一套丰富的 REST API，可轻松用于将系统集成到任何架构中。</p><p><strong> esql </strong><strong> 技能的功能：</strong></p><ul><li><p><strong>发现索引和模式：</strong>智能体可以使用该技能的内置工具列出可用索引并获取字段映射。例如，在为电子商务数据集编写查询之前，智能体可以在 <strong><code>kibana_sample_data_ecommerce</code></strong> 上运行模式检查，以了解可用的字段，如 <strong><code>taxful_total_price</code></strong> 或 <strong><code>category</code></strong>。</p></li><li><p><strong>无缝自然语言翻译：</strong>该技能不仅仅为智能体提供了一个简单的参考手册；它还提供了一个专门的指南，用于解读用户意图。当您用自然语言输入请求（如“按服务分组显示平均响应时间”）时，智能体会使用技能捆绑的模式匹配功能，将您的文字立即转换为正确的 ES|QL 聚合、筛选条件和命令。</p></li><li><p><strong>自我纠正：</strong>如果查询失败（例如由于类型不匹配或语法错误），该技能会返回生成的查询以及确切的 Elasticsearch 错误信息，使智能体能够立即修复查询并再次尝试，而无需您进行干预。</p></li></ul><p>由于 <code>esql</code> 技能也作为工具在 <code>elastic-agent-builder</code> MCP 服务器中可用，我们需要暂时禁用该服务器。您可以使用以下命令禁用它：</p>/mcp disable elastic-agent-builder<p>然后，您只需在 Gemini CLI 中输入类似这样的提示：</p>Find the top 5 product categories by total sales revenue in the kibana_sample_data_ecommerce index<p>代理将：</p><ul><li><p>认识到 <code>esql</code> 技能的必要性。</p></li><li><p>检查 <strong><code>kibana_sample_data_ecommerce</code></strong> 的模式。</p></li><li><p>构建一个 ES|QL 查询，比如：<code>FROM kibana_sample_data_ecommerce | STATS total_revenue = SUM(taxful_total_price) BY category.keyword | SORT total_revenue DESC | LIMIT 5</code>。</p></li><li><p>针对 Elasticsearch API 执行查询。</p></li><li><p>直接在终端中向您展示最终答案。</p></li></ul><p>在这里，我们分享了一个 Gemini 对先前提示的响应示例：</p>───────────────────────────────────────────────────────────
&gt; Find the top 5 product categories by total sales revenue in the kibana_sample_data_ecommerce index   ───────────────────────────────────────────────────────────
✓  Activate Skill "esql": Interact with Elasticsearch using ES|QL and curl. Use when querying, managing indices,  …
Skill esql activated. Resources loaded from /home/user/.gemini/extensions/elasticsearch/skills/esql: 
Showing up to 200 items (files + folders).                                                                     /home/user/.gemini/extensions/elasticsearch/skills/esql/                                                            ├───SKILL.md 
└───references/
├───esql-reference.md 
├───generation-tips.md 
└───query-patterns.md

✦ I will start by exploring the mapping of the kibana_sample_data_ecommerce index to identify the fields for product category and sales revenue. Then, I will construct and execute an ES|QL query to determine the top 5 product categories by total sales revenue.

✓  Shell curl -s "${ELASTIC_URL%/}/kibana_sample_data_ecommerce/_mapping" -H "Authorization: ApiKey $(printenv ELAS…                                                                                                                       {  
   "kibana_sample_data_ecommerce": { 
     "mappings": { 
       "properties": {
         "category": { 
           "type": "text", 
           "fields": {
             "keyword": {
               "type": "keyword"
             }
           }
         }, 
         "currency": {
           "type": "keyword"
         }, 

✦ Okay, I have the mapping. The category is products.category.keyword and sales revenue is taxful_total_price. I'll now execute the ES|QL query to get the top 5 categories by revenue.

✓  Shell curl -s -X POST "${ELASTIC_URL%/}/_query" \  -H "Authorization: ApiKey $(printenv ELASTIC_API_KEY)" \  -H …
{ 
   "took": 62,
   "is_partial": false, 
   "completion_time_in_millis": 1772805644164,
   "documents_found": 4675,
   "values_loaded": 12084, 
   "start_time_in_millis": 1772805644102, 
   "expiration_time_in_millis": 1773237644087,  
   "columns": [ 
     { 
       "name": "total_revenue",    
       "type": "double"  
     }, 
     {   
       "name": "products.category.keyword",

✦ The query for top 5 product categories by revenue was successful. I'll format the returned JSON values into a   user-friendly list.

 ✓  Shell 
                             
 Top 5 product categories by total sales revenue: 
 1. Men's Clothing: 149393.91
 2. Women's Clothing: 135099.91
 3. Women's Shoes: 105479.17
 4. Men's Shoes: 91797.92
 5. Women's Accessories: 60830.31 

✦ I've found the answer; now I'll format it for clarity.

 ✓  Shell 

 Here are the top 5 product categories by total sales revenue:                                                        
                                                                      
 | Rank | Category              | Total Revenue | 
 |------|-----------------------|---------------| 
 | 1    | Men's Clothing        | 149,393.91    |
 | 2    | Women's Clothing      | 135,099.91    |
 | 3    | Women's Shoes         | 105,479.17    |
 | 4    | Men's Shoes           | 91,797.92     | 
 | 5    | Women's Accessories   | 60,830.31     | 

✦ I've formatted and presented the answer. I'm finished.
 ───────────────────────────────────────────────────────────<p>值得注意的是，Gemini 模型如何通过显示其遵循的所有步骤来生成最终响应。在这里，您可以清楚地看到技能对模型推理过程的影响。当模型第一次意识到需要使用某项技能或执行 shell 命令时，它会采用人机协同的方式请求权限。</p><p>通过处理模式发现、查询生成和执行的繁重工作，<code>esql</code> 技能可以让您完全专注于答案，而不是获得答案的机制。您将获得所需的数据，格式正确且直接存储在终端中，无需写一行语法或切换到其他应用。</p><h2>结论</h2><p>在本文中，我们介绍了我们最近发布的适用于 Gemini CLI 的 Elasticsearch 扩展。此扩展让您可以使用 Gemini 和 Elastic Agent Builder 提供的 Elasticsearch MCP 服务器（从 9.3.0 版本开始提供）以及 <code>/elastic</code> 命令与您的 Elasticsearch 实例进行交互。</p><p>此外，该扩展还包含一项 <code>esql</code> 技能，可以将用户的自然语言请求转换为 ES|QL 查询。这种技能在无法使用 MCP 服务器时特别有用，因为底层通信是由在终端中执行的简单 curl 命令驱动的。Elasticsearch 提供了一套丰富的 REST API，可以轻松集成到任何项目中。这在开发智能体 AI 应用时尤为有用。</p><p>有关 Gemini CLI 扩展的更多信息，请访问<a href="https://github.com/elastic/gemini-cli-elasticsearch">此处</a>的项目库。</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/gemini-cli-extension-elasticsearch</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/gemini-cli-extension-elasticsearch</guid>
    <category><![CDATA[集成]]></category>
    <category><![CDATA[智能体 AI]]></category>
    <dc:creator><![CDATA[Walter Rafelsberger,Enrico Zimuel]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt4ff43abe550941b4/6a17072ba29299fc2ad00fa4/6dfcec4a77b3dc83bf0d974417bf2e211abb1f4f-876x468.png" length="0" type="image/png"/>
    <pubDate>Tue, 17 Mar 2026 00:00:00 GMT</pubDate>
  </item>
  <item>
    <title><![CDATA[在 Google MCP Toolbox for Databases 中引入 Elasticsearch 支持]]></title>
    <description><![CDATA[了解 Google MCP Toolbox for Databases 现在如何提供 Elasticsearch 支持，并利用 ES|QL 工具将您的索引安全地集成到任何 MCP 客户端中。]]></description>
    <content:encoded><![CDATA[<p>在本文中，我们将介绍如何使用带有 <a href="https://github.com/elastic/elasticsearch">Elasticsearch</a> 的 Google MCP Toolbox 来构建一个用于从 Elasticsearch 索引中提取信息的简单工具。</p><p>我们最近为 <a href="https://github.com/googleapis/genai-toolbox">Google MCP Toolbox for Databases</a> 开源项目做出了贡献，为其添加了对 Elasticsearch 数据库的支持。</p><p>有了这项新功能，您现在可以使用 Google MCP Toolbox 连接到 Elasticsearch，并直接与数据“对话”。</p><h2>Elasticsearch</h2><p>我们需要运行一个 Elasticsearch 实例。您可以在 <a href="https://www.elastic.co/cloud">Elastic Cloud</a> 上激活免费试用版，或使用 <a href="https://github.com/elastic/start-local">start-local</a> 脚本在本地安装：</p>curl -fsSL https://elastic.co/start-local | sh<p>这将在计算机上安装 Elasticsearch 和 Kibana，并生成用于配置 Google MCP Toolbox 的 API 密钥。</p><p>API 密钥将显示为上一条命令的输出，并存储在 elastic-start-local 文件夹的 .env 文件中。</p><h2>安装示例数据集</h2><p>安装完成后，您可以使用启动本地脚本（存储在 .env 文件中）生成的用户名 <em>elastic</em> 和密码登录 Kibana。</p><p>您可以安装 Kibana 提供的<strong>电子商务订单</strong>数据集。它包含一个名为 <strong>kibana_sample_data_ecommerce</strong> 的单个索引，其中包含来自一家电子商务网站的 4,675 个订单的信息。对于每笔订单，我们都有以下信息：</p><ul><li><p>客户信息（姓名、ID 号码、出生日期、电子邮件等）</p></li><li><p>订单日期</p></li><li><p>订单编号</p></li><li><p>产品（包含价格、数量、ID、类别、折扣等信息的所有产品列表）</p></li><li><p>SKU</p></li><li><p>总价（不含税，含税）</p></li><li><p>总数量</p></li><li><p>地理信息（城市、国家、洲、位置、地区）</p></li></ul><p>要安装示例数据，请在 Kibana 中打开“<strong>集成</strong>”页面（在顶部搜索栏中搜索“集成”），然后安装“示例数据”。有关详细信息，请参阅此处的文档：<a href="https://www.elastic.co/docs/explore-analyze/#gs-get-data-into-kibana">https://www.elastic.co/docs/explore-analyze/#gs-get-data-into-kibana</a>。</p><p>本文旨在展示如何轻松配置 Google MCP Toolbox 以连接到 Elasticsearch，并使用自然语言与 <strong>kibana_sample_data_ecommerce</strong> 索引进行交互。</p><h2>Google MCP 工具箱</h2><p>Google MCP Toolbox 是一款开源 MCP 服务器，旨在使应用程序和 AI 代理能够轻松、安全、高效地与数据库进行交互。该项目以前称为“GenAI Toolbox for Databases”，在与<a href="https://www.anthropic.com/news/model-context-protocol">模型上下文协议</a> (MCP) 完全兼容后重新命名。其目的是通过在幕后处理连接池、身份验证、可观察性和其他操作问题，消除传统上需要将代理连接到数据库的繁重工作。</p><p>Toolbox 的核心功能是允许开发人员定义可重用的高级工具，封装数据库交互操作。然后，任何兼容 MCP 的客户端（如 AI 代理）都可以调用这些工具，而无需客户端执行低级 SQL 查询或管理数据库连接。这种方法大大减少了构建数据库感知代理所需的模板代码量，只需几行应用程序逻辑就能集成高级数据操作。一旦定义工具，就可以在多个代理、框架或语言之间共享（图 1）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blte90070297ee83546/6a16fa29964cea694b08b972/137cea290bb70ad5da21853f9a6358cef4cf7451-1248x1056.png" alt="" /><p>使用 Toolbox 的一大优势是内置的安全模型。原生支持 OAuth2 和 OIDC 等身份验证流程，使开发者避免在代理中处理或存储敏感的数据库凭据。该平台还通过 OpenTelemetry 提供可观测性功能（包括指标和跟踪），这对于调试、监控和生产部署至关重要。总而言之，MCP Toolbox 是一个统一、安全和可扩展的接口，可从任何支持 MCP 的系统与您的数据进行交互。</p><h2>如何安装 MCP Toolbox</h2><p>您可以使用以下命令在 Linux 上安装 MCP Toolbox 服务器：</p>export VERSION=0.21.0
curl -L -o toolbox https://storage.googleapis.com/genai-toolbox/v$VERSION/linux/amd64/toolbox
chmod +x toolbox<p>如果您想将其安装在 macOS 或 Windows 上，您可以按照<a href="https://googleapis.github.io/genai-toolbox/getting-started/introduction/#installing-the-server">此处</a>的详细说明进行操作。</p><h2>配置适用于 Elasticsearch 的 Toolbox</h2><p>要为 Elasticsearch 配置 MCP Toolbox，我们需要创建一个 <strong>tools.yaml</strong> 文件，如下所示：</p>sources:
  my-cluster:
    kind: elasticsearch
    addresses:
      - http://localhost:9200
    apikey: &lt;insert-here-api-key&gt;

tools:
  customer-orders:
    kind: elasticsearch-esql
    source: my-cluster
    description: Get the orders made by a customer identified by name.
    query: |
    	FROM kibana_sample_data_ecommerce | WHERE MATCH(customer_full_name, ?name, {"operator": "AND"})
    parameters:
      - name: name
        type: string
        description: The customer name.

toolsets:
  elasticsearch-tools:
    - customer-orders<p>您需要使用有效的 Elasticsearch API 密钥替换 <strong>&lt;insert-here-api-key&gt;</strong> 值。如果您使用 start-local 在本地运行 Elasticsearch，则可以在.env 文件中找到由 start-local 生成的 API 密钥，位于 <strong>ES_LOCAL_API_KEY</strong> 变量下。如果您正在使用 Elastic Cloud，则可以按照<a href="https://www.elastic.co/docs/deploy-manage/api-keys/elastic-cloud-api-keys">此处</a>所描述的步骤生成 API 密钥。</p><p>之前的工具包含以下适用于 Elasticsearch 的 ES|QL 查询：</p><p>如果您不熟悉 ES|QL，它是由 Elastic 开发的一种类似于 SQL 的查询语言，可用于在一个或多个索引中进行搜索。您可以在<a href="https://www.elastic.co/docs/reference/query-languages/esql">此处</a>的正式文档中阅读有关 ES|QL 的更多信息。</p><p>上述查询使用 <strong>?name</strong> 参数（问号表示参数）搜索存储在 <strong>kibana_sample_data_ecommerce</strong> 索引中所有包含指定客户姓名的订单。</p><p>在之前的 YAML 配置中，客户名称使用字符串类型并附带描述“客户名称”来定义。</p><p>此工具可用于回答有关客户订单的问题——例如：<em>客户 Foo 在 2025 年 10 月下了多少订单？</em></p><p>对工具及其参数的描述对于从用户的自然语言请求中提取相关信息至关重要。这种提取是通过大型语言模型 (LLM) 的<strong>函数调用</strong>功能实现的。在实践中，LLM 可以确定需要执行哪个函数（工具）以获取必要的信息，并为该函数指定适当的参数。</p><p>有关函数调用的更多信息，我们建议阅读 Ashish Tiwari 撰写的《<a href="https://www.elastic.co/search-labs/blog/function-calling-with-elastic">使用 Elasticsearch 进行 OpenAI 函数调用</a>》。</p><h2>运行 Toolbox 服务器</h2><p>您可以使用之前的 tools.yaml 文件，通过以下命令运行 MCP 工具箱：</p>./toolbox --tools-file tools.yaml --ui<p><strong>—ui</strong> 参数在 <a href="http://127.0.0.1:5000/ui">http://127.0.0.1:5000/ui</a> 上运行 Web 应用程序（图 2）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt0fb3953fae603572/6a16fa2aa6c2b92763e794fb/3caf2339b632bafd5847af1ed8b33b518a25b8a2-1600x314.png" alt="" /><p>您可以选择<strong>工具</strong> &gt; <strong>客户订单</strong>，并在参数<strong>名称</strong>（例如，Gwen Sanders）中插入客户名称。然后点击<strong>“运行工具”</strong>按钮。您应该会看到如图 3 所示的 JSON 响应。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltca02df8c78cb39ff/6a16fa2c961e6909b5c4cd22/b167e0142afb8919d9cedf6d0fa431d33d0e55f8-1600x933.png" alt="" /><p>设置已完成，MCP Toolbox 可以执行<strong>客户订单</strong>工具与 Elasticsearch 进行通信，运行 ES|QL 查询。</p><h2>将 MCP Toolbox 与 Gemini CLI 结合使用</h2><p>我们可以使用任何 MCP 客户端与 MCP Toolbox for Databases 进行通信。例如，我们可以使用命令行工具 <a href="https://github.com/google-gemini/gemini-cli">Gemini CLI</a> 来使用 Gemini。您可以按照<a href="https://geminicli.com/docs/get-started/installation/">此处</a>提供的说明安装 Gemini CLI。</p><p>Gemini CLI 为 MCP Toolbox 提供了一个预配置扩展程序，可在 <a href="https://github.com/gemini-cli-extensions/mcp-toolbox">gemini-cli-extensions/mcp-toolbox</a> 上获取。您可以通过运行以下命令来安装此扩展程序：</p>gemini extensions install https://github.com/gemini-cli-extensions/mcp-toolbox<p>安装完成后，您需要进入为 MCP Toolbox 存储 tools.yaml 配置文件的目录，并按如下步骤执行 Gemini CLI（此步骤是 Gemini CLI 与 MCP Toolbox 自动配置所必需的）：</p>gemini<p>您应该会看到图 4 中所示的输出广告。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltf7245c10b9e32cd6/6a16fa2d964cea073208b976/0f22df6d3da13c1dc50dcb560414fa7c630eb9a7-1434x341.png" alt="" /><p>您可以使用以下命令检查 MCP Toolbox 是否已连接：</p>/mcp list<p>您应该能看到已列出<strong>客户订单</strong>工具的 <strong>mcp_toolbox</strong>（图 5）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blte857b42dbe604203/6a16fa2f8b73cb531b189e33/97edbc40de9e44f469f6f3a09427532be167de0e-493x155.png" alt="" /><p>如果 MCP Toolbox 已连接到 Gemini CLI，我们现在可以尝试问一些问题，例如：“<em>给我客户 Gwen Sanders 的订单</em>。”然后，Gemini CLI 将向 mcp_toolbox 服务器请求执行客户订单工具的权限（参见图 6）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltfb7ea752c1a39da7/6a16fa30cdacbfdf937d27ff/c052f3b5e49436903b804280c0065f67ee02444b-1432x284.png" alt="" /><p>确认后，Gemini CLI 将向 MCP Toolbox 执行请求，得到 JSON 响应结果，并使用它来格式化响应（图 7）。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltb9f6e04987137a9f/6a16fa320811ae2297e9fef7/7ea5128f1705951c2757af6da4b456d394d4a080-1432x734.png" alt="" /><p>Gemini CLI 的响应将报告 Gwen Sanders 只下了一个订单，包含 2 件产品，总价为 132 欧元。</p><h2>MCP 工具箱 SDK</h2><p>Google MCP Toolbox 还提供一个 SDK，可用于访问用 Go、Python 和 Javascript 编写的程序中的所有功能。</p><p>例如，Python SDK 可在 Github 上获取，页面如下：<a href="https://github.com/googleapis/mcp-toolbox-sdk-python">https://github.com/googleapis/mcp-toolbox-sdk-python</a>。</p><p>我们需要创建一个简单的代理来连接 MCP 工具箱。我们需要安装以下软件包：</p>pip install toolbox-core
pip install google-adk<p>然后使用以下命令创建一个新的代理项目：</p>adk create my_agent<p>这会创建一个名为 <strong>my_agent</strong> 的新目录，其中包含文件 <strong>agent.py</strong>。</p><p>使用以下内容更新 <strong>my_agent/agent.py</strong>，以连接到 Toolbox：</p>from google.adk import Agent
from google.adk.apps import App
from toolbox_core import ToolboxSyncClient

client = ToolboxSyncClient("http://127.0.0.1:5000")

root_agent = Agent(
    name='root_agent',
    model='gemini-2.5-flash',
    instruction="You are a helpful AI assistant designed to search information about a dataset of ecommerce orders.",
    tools=client.load_toolset(),
)

app = App(root_agent=root_agent, name="my_agent")<p>创建一个 <strong>.env</strong>文件，其中包含您的 Google API 密钥：</p>echo 'GOOGLE_API_KEY="YOUR_API_KEY"' &gt; my_agent/.env<p>最后，我们可以运行代理并观察结果。要执行代理，您可以运行以下命令：</p>adk run my_agent<p>或者，您也可以通过 Web 接口提供服务：</p>adk web --port 8000<p>在这两种情况下，您都可以使用问答接口与 MCP Toolbox 进行交互。例如，您可以提出前一个问题：<em>给我客户 Gwen Sanders 的订单</em>。</p><p>有关不同 SDK 的更多信息，可以参考<a href="https://googleapis.github.io/genai-toolbox/sdks/">此文档页面</a>。</p><h2>结论</h2><p>在本文中，我们演示了 Elasticsearch 与 Google MCP Toolbox for Databases 的集成。使用简单的 YAML 配置文件，我们可以定义一组工具，这些工具使用 ES|QL 语言将自然语言问题转换为 Elasticsearch 查询。</p><p>我们展示了如何与 kibana_sample_data_ecommerce 数据集进行交互，该数据集包含来自电子商务网站的订单。通过这个配置文件，我们可以简单地运行 MCP Toolbox 服务器并从任何 MCP 客户端连接到它。</p><p>最后，我们演示了如何使用 Gemini CLI 作为客户端连接到 MCP Toolbox for Databases 并查询存储在 Elasticsearch 中的电子商务数据。我们执行了自然语言查询，以检索有关特定客户（以姓名标识）的订单信息。</p><p>随着 MCP 生态系统的不断发展，这种模式——轻量级工具定义，由安全、生产就绪的基础架构支持——为构建越来越强大、数据感知的代理提供了新的机会，且所需努力最小。无论您是在本地尝试 Elastic 的示例数据集，还是将搜索功能集成到更大的应用程序中，MCP 工具箱都为使用自然语言与 Elasticsearch 数据进行交互提供了可靠、可扩展的基础。</p><p>有关代理 AI 应用程序开发的更多信息，您可以阅读 Anish Mathur 和 Dana Juratoni 撰写的<a href="https://search-labs-redesign.vercel.app/search-labs/blog/ai-agentic-workflows-elastic-ai-agent-builder">《使用 Elasticsearch 构建 AI 代理工作流》</a>。</p><p>有关 Google MCP Toolbox 的更多信息，请访问 <a href="https://googleapis.github.io/genai-toolbox/getting-started/introduction/">https://googleapis.github.io/genai-toolbox/getting-started/introduction/</a>。</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/google-mcp-toolbox-elasticsearch-support</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/google-mcp-toolbox-elasticsearch-support</guid>
    <category><![CDATA[ES|QL]]></category>
    <category><![CDATA[智能体 AI]]></category>
    <dc:creator><![CDATA[Enrico Zimuel,Laurent Saint-Félix]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt72d49893c51407cf/6a16fa33cf4f2502bab2cf7e/425a48691f436ed47c9bdfaf5d561ac122b2c472-1062x668.png" length="0" type="image/png"/>
    <pubDate>Fri, 12 Dec 2025 00:00:00 GMT</pubDate>
  </item>
  <item>
    <title><![CDATA[从 ES|QL 到 PHP 对象]]></title>
    <description><![CDATA[学习如何在 PHP 中执行和管理 ES|QL 查询。请按照本指南将 ES|QL 结果映射到 PHP 对象或自定义类。]]></description>
    <content:encoded><![CDATA[<p>从 elasticsearch-php<a href="https://github.com/elastic/elasticsearch-php/releases/tag/v8.13.0">v8.13.0</a>开始，您可以执行<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/esql.html">ES|QL</a>查询，并将结果映射到<a href="https://www.php.net/manual/en/class.stdclass.php">stdClass</a>或自定义类的 PHP 对象。</p><h2>ES|QL</h2><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/esql.html">ES|QL</a>是 Elasticsearch 8.11.0 中引入的一种新的 Elasticsearch 查询语言。目前，它还处于技术预览阶段。它为过滤、转换和分析存储在 Elasticsearch 中的数据提供了一种强大的方法。</p><p>它利用"管道" (<code>|</code>) 来逐步操作和转换数据。通过这种方法，用户可以进行一系列操作，其中一个操作的输出将成为下一个操作的输入，从而实现复杂的数据转换和分析。</p><p>例如，下面的查询返回<code>sample_data</code> 索引的前 3 个文档（行）：</p>FROM sample_data
| LIMIT 3
<img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt8b0310cb335872b7/6a17d7eab1e113258679f0df/c23aee777bacdf90c63b717fd9458207dfc0511d-864x284.png" alt="ES|QL 生成表格" /><h2>使用案例：官方 PHP 客户端中的 ES|QL 功能</h2><p>为了说明在官方 PHP 客户端中开发的 ES|QL 功能，我们在 Elasticsearch 中存储了一个包含 81,828 本图书（54.4 MB）的<a href="https://github.com/elastic/elasticsearch-php-examples/blob/main/examples/ESQL/data/books.csv">CSV 文件</a>，其中包括以下信息：</p>Title;Descrition;Author;Year;Publisher;Ratings
<p>我们从公开的<a href="https://www.kaggle.com/datasets/mohamedbakhet/amazon-books-reviews">亚马逊图书评论数据集中</a>提取了这份清单。</p><p>我们使用以下 Elasticsearch 映射创建了<code>books</code> 索引：</p>'mappings' : {
    'properties': {
        'title': {
            'type': 'text'
        },
        'description': {
            'type': 'text'
        },
        'author': {
            'type': 'text'
        },
        'year': {
            'type': 'short'
        },
        'publisher': {
            'type': 'keyword'
        },
        'rating': {
            'type': 'half_float'
        }
    }
}
<p><code>rating</code> 值是从 2.9 GB 的<a href="https://www.kaggle.com/datasets/mohamedbakhet/amazon-books-reviews?select=Books_rating.csv">Books_rating.csv</a>文件中提取的评论排名平均值。</p><p><a href="https://github.com/elastic/elasticsearch-php-examples/blob/main/examples/ESQL/bulk.php">在这里</a>，你可以找到我们用来批量导入 Elasticsearch 中所有图书的 PHP 脚本。使用 PHP 8.2.17 进行批量操作耗时 7 秒，占用 28 MB 内存。使用建议的映射后，Elasticsearch 中的索引大小约为 62 MB。</p><h2>将 ES|QL 结果映射到 PHP 对象或自定义类</h2><p>我们可以使用<code>esql()-&gt;query()</code> 端点在 PHP 中执行 ES|QL 查询。查询结果是一个表格数据结构。这在 JSON 中使用<code>columns</code> 和<code>values</code> 字段来表示。在<code>columns</code> 字段中，我们有<code>name</code> 和<code>type</code> 的定义。</p><p>下面是一个 ES|QL 查询示例，用于检索斯蒂芬-金著作中按用户评论排名排序的前 10 本书籍：</p>$query = &lt;&lt;&lt;EOD
    FROM books
    | WHERE author == "Stephen King"
    | SORT rating DESC
    | LIMIT 10
EOD;

$result = $client-&gt;esql()-&gt;query([
    'body' =&gt; ['query' =&gt; $query]
]);
<p>来自 Elasticsearch 的 JSON 结果如下：</p>{
    "columns": [
        { "name": "author", "type": "text" },
        { "name": "description", "type": "text" },
        { "name": "publisher", "type": "keyword" },
        { "name": "rating", "type": "double" },
        { "name": "title", "type": "text" },
        { "name": "year", "type": "integer" }
    ],
    "values": [
        [
            "Stephen King",
            "The author ...",
            "Turtleback",
            5.0,
            "How writers write",
            2002
        ],
        [
            "Stephen King",
            "In Blockade Billy, a retired coach...",
            "Simon and Schuster",
            5.0,
            "Blockade",
            2010
        ],
        [
            "Stephen King",
            "A chilling collection of twenty horror stories.",
            "Signet Book",
            4.55859375,
            "Night Shift (Signet)",
            1979
        ],
        ...
    ]
}
<p>在这个例子中，我们有 6 个与一本书相关的属性（作者、描述、出版商、评分、标题、年份）和 10 个结果，都是斯蒂芬-金的书。</p><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/esql-limitations.html#esql-supported-types">这里</a>列出了 ES|QL 支持的所有类型。</p><p><code>$result</code> 响应对象可以数组、字符串或对象的形式访问（更多信息，请参见<a href="https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/connecting.html#client-usage">此处</a>）。</p><p>使用对象接口，我们可以使用属性和索引访问值。例如，<code>$result-&gt;values[0][4]</code> 返回列表中第一本书（0）的书名（4），<code>$result-&gt;values[1][3]</code> 返回第二本书（1）的等级分（3），等等。请记住，PHP 中数组的索引是从 0 开始的。</p><p>对于某些使用情况，这个接口已经足够好了，但大多数情况下，我们希望得到一个对象数组的结果。</p><p>要将结果映射到对象数组中，我们可以使用 elasticsearch-php 的新功能<a href="https://github.com/elastic/elasticsearch-php/issues/1398">mapTo()。</a></p><p>该功能可直接在<a href="https://github.com/elastic/elasticsearch-php/blob/main/src/Response/Elasticsearch.php">Elasticsearch 响应对象</a>中使用。这意味着您可以通过以下方式访问它：</p>$books = $result-&gt;mapTo(); // Array of stdClass
foreach ($books as $book) {
    printf(
        "%s, %s, %d, Rating: %.2f\n",
        $book-&gt;author,
        $book-&gt;title,
        $book-&gt;year,
        $book-&gt;rating
    );
}
<p>如果您有一个自定义的图书类，可以使用它来映射结果，如下所示：</p>class Book
{
    public string $author;
    public string $title;
    public string $description;
    public int $year;
    public float $rating;
}

$books = $result-&gt;mapTo(Book::class); // Array of Book
<p>如果您的类除了 ES|QL 结果中包含的属性外还有其他属性，这也同样有效。<code>mapTo()</code> 函数将只使用作为 ES|QL 结果列返回的属性。</p><p>您可以<a href="https://github.com/elastic/elasticsearch-php-examples/tree/main/examples/ESQL">在此</a>下载本文中报告的所有示例。</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/esql-php-map-object-class</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/esql-php-map-object-class</guid>
    <category><![CDATA[ES|QL]]></category>
    <category><![CDATA[PHP]]></category>
    <dc:creator><![CDATA[Enrico Zimuel]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt99f5ab85c0713977/6a17d7ebfbc5f8072b491918/aea56270f48cb64130d1b515b983434e0960dc2f-500x500.png" length="0" type="image/png"/>
    <pubDate>Mon, 08 Apr 2024 00:00:00 GMT</pubDate>
  </item>
  </channel>
</rss>