MCPInstall

elasticsearch-query-optimization

Diagnose slow Elasticsearch Query DSL searches and propose measured fixes. Use when a search is slow, profile output shows an expensive clause, exact-match filters sit in scoring context, or leading wildcards dominate latency. Ground every recommendation in search profiling — move non-scoring clauses to filter context, eliminate leading wildcards, and re-profile to confirm improvement.

Installs
1.1K
Last 24h
+21
Trending rank
#5679
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/elastic/agent-skills --skill elasticsearch-query-optimization
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads elasticsearch-query-optimization automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Elasticsearch Query DSL Optimization

Diagnose why a Query DSL search is slow, identify the dominant cost from the profile (not guesswork), rewrite the query to remove that cost while preserving match semantics, and re-measure with profiling enabled.

<!-- begin-partial: preamble -->

Environment Configuration

This skill executes Elasticsearch operations through the elastic CLI. If the elastic CLI is not installed, tell the user what it is needed for. Do not guess credentials, call the HTTP API directly, or attempt other workarounds.

This skill references operations in HTTP-shorthand form (e.g., GET /, GET /_cat/indices, GET /{index}/_mapping, GET /{index}/_settings/index.mode, POST /_query). The Operations table at the end of this document maps each shorthand to the equivalent elastic CLI command — always use the CLI rather than calling the HTTP API directly.

<!-- end-partial: preamble -->

Scope: Query DSL searches via POST /{index}/_search. This skill does not migrate queries to ES|QL — it optimizes the existing bool/match/term/wildcard structure the user already runs.

Ground rule: Never recommend "add shards" or "scale hardware" as the primary fix when the profile names a specific clause (for example WildcardQuery at ~3.8s). Fix the query first; infrastructure changes require evidence the query is already optimal.

Process

  1. Confirm connectivity and locate the target index. Call GET /. If the call fails, stop — do not guess endpoints or credentials. When the user names an index pattern (for example logs-*), narrow candidates with GET /_cat/indices and pick the index or pattern the query actually targets.

    Decision: proceed only when the index is known. Data needed: index name or pattern, and the slow Query DSL body (from the user or from a saved search).

  2. Profile the slow query to find the dominant cost. Call POST /{index}/_search with "profile": true and the user's query unchanged. Read took, then inspect profile.shards[].searches[].query — sort child collectors by time_in_nanos and identify the top contributor.

    Decision: classify the bottleneck from profile evidence:

    • TermQuery / PointRangeQuery / MatchNoDocsQuery inside must alongside a scoring clause — exact-match or range filters are being scored unnecessarily. Likely fix: move them to filter context (step 4a).
    • WildcardQuery with a leading * (for example message:*timeout*) — cannot use the inverted index; scans terms per document. Likely fix: remove the leading wildcard (step 4b).
    • MatchQuery on a text field — expected scoring cost; optimize only if profile shows it dominates after filter-context fixes.
    • High aggregation time — separate from query tuning; profile the agg tree (out of scope unless the user asked about aggs).

    Data needed: profile tree with type, description, time_in_nanos, and breakdown (especially next_doc for wildcards). Quote the top contributor verbatim when explaining the diagnosis.

  3. Inspect field mappings before rewriting. Call GET /{index}/_mapping. For every clause you will move or rewrite, confirm the field type:

    • term / terms / filter on exact values — field must be keyword (or another non-analyzed type). A term on a text field is a common bug; if types are wrong, say so and suggest the correct sub-field (for example service.keyword) or a mapping change — do not silently rewrite.
    • match / match_phrase — target a text field (analyzed).
    • wildcard — works on keyword or wildcard types; leading * still forces a scan regardless of type.

    Decision: only propose rewrites that match confirmed types. Data needed: mapping for each field referenced in the query.

  4. Rewrite the query to remove the profiled bottleneck.

    4a. Move non-scoring clauses from must to filter

    When exact-match term/terms/range/match on a keyword (or other non-scoring intent) clauses sit in must alongside a full-text match that should drive relevance:

    • Move exact-match clauses into bool.filter (or a filter array entry).
    • Keep only clauses that must affect _score in bool.must (typically the full-text match).

    Why: filter context skips scoring and participates in the filter/bitset cache on repeated queries. Semantics: the same documents match; only scoring and performance change — state this explicitly.

    Example rewrite pattern:

    {
      "query": {
        "bool": {
          "filter": [{ "term": { "status": "active" } }, { "term": { "tenant_id": "acme" } }],
          "must": [{ "match": { "description": "wireless keyboard" } }]
        }
      }
    }
    

    4b. Eliminate leading wildcards

    When the profile shows WildcardQuery with description like message:*timeout* and high next_doc time, the leading * prevents index lookup. Choose a fix based on mapping and user intent (substring vs prefix vs exact):

    IntentPreferred rewrite
    Full-text substring in logsmatch or match_phrase on the analyzed message text field
    Literal substring on keywordwildcard-typed field, or reindex with ngram analyzer
    Prefix only (timeout*)prefix query on keyword, or edge ngram at index time

    Also move any non-scoring exact match (for example { "match": { "service": "checkout" } } on a keyword) into filter — use term on the keyword field when the mapping confirms it.

    Example rewrite pattern:

    {
      "query": {
        "bool": {
          "filter": [{ "term": { "service.keyword": "checkout" } }],
          "must": [{ "match": { "message": "timeout" } }]
        }
      }
    }
    

    Adjust field names (service vs service.keyword) to match the mapping from step 3.

    4c. Optional — validate rewrite before profiling

    When semantics are uncertain (for example changing wildcard to match may include analyzed tokens the wildcard excluded), call POST /{index}/_validate/query?explain=true with the rewritten query and read the explanation for obvious mismatches.

    Decision: pick the smallest rewrite that addresses the profiled cost. Data needed: rewritten Query DSL body.

  5. Re-profile the rewritten query and compare. Call POST /{index}/_search again with "profile": true and the rewritten query. Compare took and the top profile collector to the baseline from step 2.

    Decision: report success only when the dominant collector changed or time_in_nanos dropped materially. If the profile still shows a leading wildcard or scored filters, iterate — do not declare victory from took alone without profile confirmation.

    Data needed: before/after profile summaries (top collector type, description, time_in_nanos).

  6. Report findings in this order.

    1. Root cause — quote the profile (for example "WildcardQuery message:*timeout* ≈ 3.8s, mostly next_doc").
    2. Rewrite — show the optimized bool structure with filter vs must separation.
    3. Mapping notes — keyword vs text confirmations from GET /{index}/_mapping.
    4. Measured improvement — before/after profile or took from step 5.
    5. Semantic caveat — only if the rewrite could change which documents match (for example match vs substring wildcard).

Guidelines

  • Profile first. If the user supplies a profile summary, use it — but still recommend re-profiling after changes.
  • Filter is for equality, must is for relevance. Status, tenant ID, service name, and time ranges rarely belong in must when a text query drives ranking.
  • Leading wildcards are almost never the right fix for log search. Prefer analyzed match/match_phrase; reserve wildcard for suffix patterns (timeout*) on keyword or wildcard-typed fields.
  • Do not conflate slow with wrong. A slow query can return correct results; optimization preserves the result set unless you explicitly warn about a semantic trade-off.
  • Deep reference: profile collector types, filter-cache behavior, and wildcard alternatives — references/query-optimization-reference.md.

Examples

Unscored terms in must

Input: bool.must contains term on status, term on tenant_id, and match on description.

Diagnosis: profile shows scored TermQuery collectors alongside MatchQuery; exact filters do not need scoring.

Fix: move both term clauses to filter; keep match in must. Confirm status and tenant_id are keyword.

Leading wildcard dominates latency

Input: wildcard message:*timeout* plus match on service in must. Profile: WildcardQuery ~3.8s.

Diagnosis: leading * forces term enumeration; not an index/shard problem.

Fix: match on analyzed message; move service to filter as term on keyword. Re-profile — expect WildcardQuery to disappear or shrink to negligible time.

Operations

HTTP API (shorthand)elastic CLI command
GET /elastic es info
GET /_cat/indiceselastic es cat indices --index '<pattern>'
GET /{index}/_mappingelastic es indices get-mapping --index '<index>'
POST /{index}/_searchelastic es search --index '<index>' --input-file '<search-body.json>'
POST /{index}/_validate/query?explain=trueelastic es indices validate-query --index '<index>' --explain true --query '<json>'

Include "profile": true in the search JSON body (or pass --profile true) when profiling in steps 2 and 5.

FAQ

What does the elasticsearch-query-optimization skill do?

Diagnose slow Elasticsearch Query DSL searches and propose measured fixes. Use when a search is slow, profile output shows an expensive clause, exact-match filters sit in scoring context, or leading wildcards dominate latency. Ground every recommendation in search profiling — move non-scoring clauses to filter context, eliminate leading wildcards, and re-profile to confirm improvement.

How do I install elasticsearch-query-optimization?

Run npx skills add https://github.com/elastic/agent-skills --skill elasticsearch-query-optimization in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/elasticsearch-query-optimization/ (personal) or .claude/skills/elasticsearch-query-optimization/ (project).

Which AI agents can use elasticsearch-query-optimization?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is elasticsearch-query-optimization safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains elasticsearch-query-optimization?

It is published by elastic in elastic/agent-skills. It has 1,087 recorded installs.

More from elastic/agent-skills

View all →

elasticsearch-esql

elastic/agent-skills

Execute ESQL (Elasticsearch Query Language) queries, use when the user wants to query Elasticsearch data, analyze logs, aggregate metrics, explore data, or create charts and dashboards from ESQL results.

AI & Agents4.8K installs

elasticsearch-onboarding

elastic/agent-skills

Help developers new to Elasticsearch get from zero to a working search experience. Guide them through understanding their intent, mapping their data, and building a search experience with best practices baked in. Use this when the user shows intent to build search-related functionality, asks about Elasticsearch-related concepts for their use case, or expresses the need for help getting started with Elasticsearch.

AI & Agents4.4K installs

kibana-dashboards

elastic/agent-skills

Create and manage Kibana Dashboards and Lens visualizations. Use when you need to define dashboards and visualizations declaratively, version control them, or automate their deployment.

AI & Agents4.3K installs

security-case-management

elastic/agent-skills

Create, search, update, and manage SOC cases via the Kibana Cases API. Use when tracking incidents, linking alerts to cases, adding investigation notes, or managing triage output.

Security4.1K installs

kibana-alerting-rules

elastic/agent-skills

Create and manage Kibana alerting rules. Use when creating, updating, or managing rule lifecycle (enable, disable, mute, snooze), choosing metric threshold rule types and params, or read-only find/list with tag filters.

AI & Agents4K installs

kibana-agent-builder

elastic/agent-skills

Create and manage Kibana Agent Builder agents and custom tools. Use when asked to create, update, delete, test, or inspect agents or tools in Agent Builder, or when the user wants to understand what agents or tools already exist.

AI & Agents4K installs

Popular ai & agents skills

View category →

google-agents-cli-publish

google/agents-cli

This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).

AI & Agents513.9K installs

google-agents-cli-eval

google/agents-cli

This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).

AI & Agents513.5K installs

skill-creator

anthropics/skills

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

OfficialAI & Agents416.4K installs

codex-pet

prime-skills/runcomfy-agent-skills

Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.

AI & Agents402.1K installs

full-output-enforcement

leonxlnx/taste-skill

Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.

AI & Agents401K installs

executing-plans

obra/superpowers

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

AI & Agents245.7K installs