Skip to main content
Glama
Octodet

octodet-elasticsearch-mcp

update_by_query

Modify documents in an Elasticsearch index using a query and script, handling conflicts and refresh options for controlled updates.

Instructions

Update documents in an Elasticsearch index based on a query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
conflictsNoWhat to do when version conflicts occur during the update
indexYesName of the Elasticsearch index to update documents in
maxDocsNoLimit the number of documents to update
queryYesElasticsearch query to select documents for updating
refreshNoShould the index be refreshed after the update (defaults to true)
scriptYesScript to execute on matching documents

Implementation Reference

  • The primary handler function for the \"update_by_query\" tool. Constructs the params object from inputs and calls esService.updateByQuery(params), then formats the response for the MCP server.
    async ({ index, query, script, conflicts, maxDocs, refresh }) => {
      try {
        // Create the params object with the correct type structure
        const params: Record<string, any> = {
          index,
          body: {
            query,
            script: {
              source: script.source,
              params: script.params,
            },
          },
          refresh: refresh !== false, // true by default unless explicitly set to false
        };
    
        // Add optional parameters
        if (conflicts) params.conflicts = conflicts;
        if (maxDocs) params.max_docs = maxDocs;
    
        const response = await esService.updateByQuery(params);
    
        // Format the response for better readability
        let resultText = `Update by query completed successfully in index '${index}':\n`;
        resultText += `- Total documents processed: ${response.total}\n`;
        resultText += `- Documents updated: ${response.updated}\n`;
        resultText += `- Documents that failed: ${
          response.failures?.length || 0
        }\n`;
        resultText += `- Time taken: ${response.took}ms`;
    
        // Add more detailed information if there were failures
        if (response.failures && response.failures.length > 0) {
          resultText += "\n\nFailures:";
          response.failures
            .slice(0, 5)
            .forEach((failure: any, index: number) => {
              resultText += `\n${index + 1}. ID: ${failure.id}, Reason: ${
                failure.cause?.reason || "Unknown"
              }`;
            });
    
          if (response.failures.length > 5) {
            resultText += `\n...and ${
              response.failures.length - 5
            } more failures.`;
          }
        }
    
        return {
          content: [
            {
              type: "text",
              text: resultText,
            },
          ],
        };
      } catch (error) {
        console.error(
          `Update by query failed: ${
            error instanceof Error ? error.message : String(error)
          }`
        );
        return {
          content: [
            {
              type: "text",
              text: `Error: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    }
  • Zod input schema defining parameters for the update_by_query tool: index, query, script, conflicts, maxDocs, refresh.
    {
      index: z
        .string()
        .trim()
        .min(1, "Index name is required")
        .describe("Name of the Elasticsearch index to update documents in"),
      query: z
        .record(z.any())
        .describe("Elasticsearch query to select documents for updating"),
      script: z
        .object({
          source: z
            .string()
            .min(1, "Script source is required")
            .describe("Painless script source for the update operation"),
          params: z
            .record(z.any())
            .optional()
            .describe("Optional parameters for the script"),
        })
        .describe("Script to execute on matching documents"),
      conflicts: z
        .enum(["abort", "proceed"])
        .optional()
        .describe("What to do when version conflicts occur during the update"),
      maxDocs: z
        .number()
        .int()
        .positive()
        .optional()
        .describe("Limit the number of documents to update"),
      refresh: z
        .boolean()
        .optional()
        .default(true)
        .describe(
          "Should the index be refreshed after the update (defaults to true)"
        ),
    },
  • src/index.ts:545-661 (registration)
    Registration of the \"update_by_query\" tool on the MCP server using server.tool().
    server.tool(
      "update_by_query",
      "Update documents in an Elasticsearch index based on a query",
      {
        index: z
          .string()
          .trim()
          .min(1, "Index name is required")
          .describe("Name of the Elasticsearch index to update documents in"),
        query: z
          .record(z.any())
          .describe("Elasticsearch query to select documents for updating"),
        script: z
          .object({
            source: z
              .string()
              .min(1, "Script source is required")
              .describe("Painless script source for the update operation"),
            params: z
              .record(z.any())
              .optional()
              .describe("Optional parameters for the script"),
          })
          .describe("Script to execute on matching documents"),
        conflicts: z
          .enum(["abort", "proceed"])
          .optional()
          .describe("What to do when version conflicts occur during the update"),
        maxDocs: z
          .number()
          .int()
          .positive()
          .optional()
          .describe("Limit the number of documents to update"),
        refresh: z
          .boolean()
          .optional()
          .default(true)
          .describe(
            "Should the index be refreshed after the update (defaults to true)"
          ),
      },
      async ({ index, query, script, conflicts, maxDocs, refresh }) => {
        try {
          // Create the params object with the correct type structure
          const params: Record<string, any> = {
            index,
            body: {
              query,
              script: {
                source: script.source,
                params: script.params,
              },
            },
            refresh: refresh !== false, // true by default unless explicitly set to false
          };
    
          // Add optional parameters
          if (conflicts) params.conflicts = conflicts;
          if (maxDocs) params.max_docs = maxDocs;
    
          const response = await esService.updateByQuery(params);
    
          // Format the response for better readability
          let resultText = `Update by query completed successfully in index '${index}':\n`;
          resultText += `- Total documents processed: ${response.total}\n`;
          resultText += `- Documents updated: ${response.updated}\n`;
          resultText += `- Documents that failed: ${
            response.failures?.length || 0
          }\n`;
          resultText += `- Time taken: ${response.took}ms`;
    
          // Add more detailed information if there were failures
          if (response.failures && response.failures.length > 0) {
            resultText += "\n\nFailures:";
            response.failures
              .slice(0, 5)
              .forEach((failure: any, index: number) => {
                resultText += `\n${index + 1}. ID: ${failure.id}, Reason: ${
                  failure.cause?.reason || "Unknown"
                }`;
              });
    
            if (response.failures.length > 5) {
              resultText += `\n...and ${
                response.failures.length - 5
              } more failures.`;
            }
          }
    
          return {
            content: [
              {
                type: "text",
                text: resultText,
              },
            ],
          };
        } catch (error) {
          console.error(
            `Update by query failed: ${
              error instanceof Error ? error.message : String(error)
            }`
          );
          return {
            content: [
              {
                type: "text",
                text: `Error: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
          };
        }
      }
    );
  • Helper method in ElasticsearchService class that directly calls the Elasticsearch client\'s updateByQuery method.
    async updateByQuery(params: any): Promise<any> {
      return await this.client.updateByQuery(params);
    }
  • TypeScript interface defining the structure of the result from an updateByQuery operation.
    export interface UpdateByQueryResult {
      took: number;
      total: number;
      updated: number;
      deleted?: number;
      failures?: Array<{
        id?: string;
        cause?: {
          type?: string;
          reason?: string;
        };
      }>;
      version_conflicts?: number;
      task?: string;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure but offers minimal information. It mentions the update action but doesn't disclose critical traits like whether this is a destructive operation, what permissions are required, potential performance impacts, error handling, or what the response looks like. For a mutation tool with 6 parameters and no annotation coverage, this represents a significant gap in behavioral transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that communicates the core functionality without unnecessary words. It's appropriately sized for the tool's complexity and front-loads the essential information (update documents in Elasticsearch based on query). Every word earns its place in this concise formulation.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mutation tool with 6 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't address behavioral aspects like safety, permissions, or response format, nor does it provide usage guidance relative to sibling tools. The agent would need to rely heavily on parameter schema inference and external knowledge of Elasticsearch to use this tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 6 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema (e.g., it doesn't explain query syntax, script language details, or refresh implications). With complete schema coverage, the baseline score of 3 is appropriate as the description doesn't compensate but doesn't need to given the comprehensive schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('update documents'), target resource ('in an Elasticsearch index'), and mechanism ('based on a query'), providing a specific verb+resource combination. However, it doesn't explicitly distinguish this from sibling tools like 'update_document' (single document update) or 'delete_by_query' (query-based deletion), which would require more specific differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. There's no mention of when to choose 'update_by_query' over 'update_document' (for single documents) or 'bulk' (for batch operations), nor any prerequisites or constraints for its use. The agent must infer usage context solely from the tool name and parameters.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Octodet/elasticsearch-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server