Skip to main content
Glama
Octodet

octodet-elasticsearch-mcp

delete_by_query

Remove specific documents from an Elasticsearch index by defining a query, managing conflicts, and controlling refresh behavior.

Instructions

Delete documents in an Elasticsearch index based on a query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
conflictsNoWhat to do when version conflicts occur during the deletion
indexYesName of the Elasticsearch index to delete documents from
maxDocsNoLimit the number of documents to delete
queryYesElasticsearch query to select documents for deletion
refreshNoShould the index be refreshed after the deletion (defaults to true)

Implementation Reference

  • The handler function that executes the delete_by_query tool logic. It constructs the parameters including index, query body, conflicts, max_docs, and refresh options, calls esService.deleteByQuery(params), formats the response summary including deleted count, failures, and time taken, and returns formatted text content.
    async ({ index, query, conflicts, maxDocs, refresh }) => {
      try {
        const params: Record<string, any> = {
          index,
          body: {
            query,
          },
          refresh: refresh !== false, // true by default unless explicitly set to false
        };
    
        if (conflicts) params.conflicts = conflicts;
        if (maxDocs) params.max_docs = maxDocs;
    
        const response = await esService.deleteByQuery(params);
    
        // Format the response for better readability
        let resultText = `Delete by query completed successfully in index '${index}':\n`;
        resultText += `- Total documents processed: ${response.total}\n`;
        resultText += `- Documents deleted: ${response.deleted}\n`;
        resultText += `- Deletion failures: ${
          response.failures?.length || 0
        }\n`;
        resultText += `- Time taken: ${response.took}ms`;
    
        // Add version conflicts if any occurred
        if (response.version_conflicts && response.version_conflicts > 0) {
          resultText += `\n- Version conflicts: ${response.version_conflicts}`;
        }
    
        // Add detailed failure information
        if (response.failures && response.failures.length > 0) {
          resultText += "\n\nFailures:";
          response.failures.slice(0, 5).forEach((failure: any, idx: number) => {
            resultText += `\n${idx + 1}. ID: ${
              failure.id || "unknown"
            }, 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(
          `Delete by query failed: ${
            error instanceof Error ? error.message : String(error)
          }`
        );
        return {
          content: [
            {
              type: "text",
              text: `Error: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    }
  • Zod schema defining input parameters for the delete_by_query tool: index (required string), query (required object), conflicts (optional enum), maxDocs (optional positive int), refresh (optional boolean, default true).
    {
      index: z
        .string()
        .trim()
        .min(1, "Index name is required")
        .describe("Name of the Elasticsearch index to delete documents from"),
      query: z
        .record(z.any())
        .describe("Elasticsearch query to select documents for deletion"),
      conflicts: z
        .enum(["abort", "proceed"])
        .optional()
        .describe(
          "What to do when version conflicts occur during the deletion"
        ),
      maxDocs: z
        .number()
        .int()
        .positive()
        .optional()
        .describe("Limit the number of documents to delete"),
      refresh: z
        .boolean()
        .optional()
        .default(true)
        .describe(
          "Should the index be refreshed after the deletion (defaults to true)"
        ),
    },
  • src/index.ts:664-766 (registration)
    Registration of the delete_by_query tool using server.tool, including name, description, input schema, and handler function.
    server.tool(
      "delete_by_query",
      "Delete 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 delete documents from"),
        query: z
          .record(z.any())
          .describe("Elasticsearch query to select documents for deletion"),
        conflicts: z
          .enum(["abort", "proceed"])
          .optional()
          .describe(
            "What to do when version conflicts occur during the deletion"
          ),
        maxDocs: z
          .number()
          .int()
          .positive()
          .optional()
          .describe("Limit the number of documents to delete"),
        refresh: z
          .boolean()
          .optional()
          .default(true)
          .describe(
            "Should the index be refreshed after the deletion (defaults to true)"
          ),
      },
      async ({ index, query, conflicts, maxDocs, refresh }) => {
        try {
          const params: Record<string, any> = {
            index,
            body: {
              query,
            },
            refresh: refresh !== false, // true by default unless explicitly set to false
          };
    
          if (conflicts) params.conflicts = conflicts;
          if (maxDocs) params.max_docs = maxDocs;
    
          const response = await esService.deleteByQuery(params);
    
          // Format the response for better readability
          let resultText = `Delete by query completed successfully in index '${index}':\n`;
          resultText += `- Total documents processed: ${response.total}\n`;
          resultText += `- Documents deleted: ${response.deleted}\n`;
          resultText += `- Deletion failures: ${
            response.failures?.length || 0
          }\n`;
          resultText += `- Time taken: ${response.took}ms`;
    
          // Add version conflicts if any occurred
          if (response.version_conflicts && response.version_conflicts > 0) {
            resultText += `\n- Version conflicts: ${response.version_conflicts}`;
          }
    
          // Add detailed failure information
          if (response.failures && response.failures.length > 0) {
            resultText += "\n\nFailures:";
            response.failures.slice(0, 5).forEach((failure: any, idx: number) => {
              resultText += `\n${idx + 1}. ID: ${
                failure.id || "unknown"
              }, 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(
            `Delete 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 that proxies the deleteByQuery call to the underlying Elasticsearch client.
    async deleteByQuery(params: any): Promise<any> {
      return await this.client.deleteByQuery(params);
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states the tool deletes documents, implying destructive behavior, but lacks details on permissions needed, rate limits, error handling, or what happens to conflicts. This is a significant gap for a destructive operation.

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 with zero waste. It's front-loaded with the core action and resource, making it easy to parse quickly.

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 destructive tool with no annotations and no output schema, the description is incomplete. It lacks critical behavioral context like safety warnings, permissions, or response format, leaving significant gaps for an agent to use it correctly.

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 fully documents all 5 parameters. The description adds no additional parameter semantics beyond implying query-based selection. Baseline 3 is appropriate as the schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the specific action ('Delete documents'), target resource ('in an Elasticsearch index'), and method ('based on a query'), distinguishing it from siblings like delete_document (single doc) and delete_index (entire index). It's precise and avoids tautology.

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

Usage Guidelines3/5

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

The description implies usage for bulk deletion via queries, but doesn't explicitly state when to use it versus alternatives like delete_document (single doc) or delete_index (entire index). No guidance on prerequisites or exclusions is provided.

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