
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- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads elasticsearch-query-optimization automatically when relevant.
- 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.
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
WildcardQueryat ~3.8s). Fix the query first; infrastructure changes require evidence the query is already optimal.
Process
-
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 examplelogs-*), narrow candidates withGET /_cat/indicesand 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).
-
Profile the slow query to find the dominant cost. Call
POST /{index}/_searchwith"profile": trueand the user's query unchanged. Readtook, then inspectprofile.shards[].searches[].query— sort child collectors bytime_in_nanosand identify the top contributor.Decision: classify the bottleneck from profile evidence:
TermQuery/PointRangeQuery/MatchNoDocsQueryinsidemustalongside a scoring clause — exact-match or range filters are being scored unnecessarily. Likely fix: move them tofiltercontext (step 4a).WildcardQuerywith a leading*(for examplemessage:*timeout*) — cannot use the inverted index; scans terms per document. Likely fix: remove the leading wildcard (step 4b).MatchQueryon atextfield — expected scoring cost; optimize only if profile shows it dominates after filter-context fixes.- High
aggregationtime — 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, andbreakdown(especiallynext_docfor wildcards). Quote the top contributor verbatim when explaining the diagnosis. -
Inspect field mappings before rewriting. Call
GET /{index}/_mapping. For every clause you will move or rewrite, confirm the field type:term/terms/filteron exact values — field must bekeyword(or another non-analyzed type). Atermon atextfield is a common bug; if types are wrong, say so and suggest the correct sub-field (for exampleservice.keyword) or a mapping change — do not silently rewrite.match/match_phrase— target atextfield (analyzed).wildcard— works onkeywordorwildcardtypes; 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.
-
Rewrite the query to remove the profiled bottleneck.
4a. Move non-scoring clauses from
musttofilterWhen exact-match
term/terms/range/matchon a keyword (or other non-scoring intent) clauses sit inmustalongside a full-textmatchthat should drive relevance:- Move exact-match clauses into
bool.filter(or afilterarray entry). - Keep only clauses that must affect
_scoreinbool.must(typically the full-textmatch).
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
WildcardQuerywithdescriptionlikemessage:*timeout*and highnext_doctime, the leading*prevents index lookup. Choose a fix based on mapping and user intent (substring vs prefix vs exact):Intent Preferred rewrite Full-text substring in logs matchormatch_phraseon the analyzedmessagetextfieldLiteral substring on keyword wildcard-typed field, or reindex with ngram analyzerPrefix only ( timeout*)prefixquery onkeyword, or edge ngram at index timeAlso move any non-scoring exact match (for example
{ "match": { "service": "checkout" } }on a keyword) intofilter— usetermon 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 (
servicevsservice.keyword) to match the mapping from step 3.4c. Optional — validate rewrite before profiling
When semantics are uncertain (for example changing
wildcardtomatchmay include analyzed tokens the wildcard excluded), callPOST /{index}/_validate/query?explain=truewith 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.
- Move exact-match clauses into
-
Re-profile the rewritten query and compare. Call
POST /{index}/_searchagain with"profile": trueand the rewritten query. Comparetookand the top profile collector to the baseline from step 2.Decision: report success only when the dominant collector changed or
time_in_nanosdropped materially. If the profile still shows a leading wildcard or scored filters, iterate — do not declare victory fromtookalone without profile confirmation.Data needed: before/after profile summaries (top collector
type,description,time_in_nanos). -
Report findings in this order.
- Root cause — quote the profile (for example "
WildcardQuerymessage:*timeout*≈ 3.8s, mostlynext_doc"). - Rewrite — show the optimized bool structure with filter vs must separation.
- Mapping notes — keyword vs text confirmations from
GET /{index}/_mapping. - Measured improvement — before/after profile or
tookfrom step 5. - Semantic caveat — only if the rewrite could change which documents match (for example
matchvs substringwildcard).
- Root cause — quote the profile (for example "
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
mustwhen a text query drives ranking. - Leading wildcards are almost never the right fix for log search. Prefer analyzed
match/match_phrase; reservewildcardfor suffix patterns (timeout*) on keyword orwildcard-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/indices | elastic es cat indices --index '<pattern>' |
GET /{index}/_mapping | elastic es indices get-mapping --index '<index>' |
POST /{index}/_search | elastic es search --index '<index>' --input-file '<search-body.json>' |
POST /{index}/_validate/query?explain=true | elastic 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
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.
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.
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.
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.
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.
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.
Popular ai & agents skills
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).
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).
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.
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.
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.
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