Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Elasticsearch Patterns

ASecurity

Mapping design, query optimization, aggregation patterns, index lifecycle management, and search relevance tuning.

530 stars
0 votes
0 copies
0 views
Added 5/29/2026
ai-agentstypescriptgonodeapidatabase

Works with

cliapi

Security Analysis

A100/100

Scanned 5/29/2026

$npx -y skills add vibeeval/vibecosystem --skill elasticsearch-patterns --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Elasticsearch Patterns?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Elasticsearch Patterns
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/vibeeval-elasticsearch-patterns/badge)](https://www.skillsdirectory.com/skills/vibeeval-elasticsearch-patterns)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
skill.md
---
name: elasticsearch-patterns
description: Mapping design, query optimization, aggregation patterns, index lifecycle management, and search relevance tuning.
---

# Elasticsearch Patterns

Search and analytics patterns for Elasticsearch deployments.

## Mapping Design

```json
{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "id": { "type": "keyword" },
      "title": {
        "type": "text",
        "analyzer": "standard",
        "fields": {
          "keyword": { "type": "keyword" },
          "autocomplete": {
            "type": "text",
            "analyzer": "autocomplete_analyzer"
          }
        }
      },
      "description": {
        "type": "text",
        "analyzer": "standard"
      },
      "price": { "type": "scaled_float", "scaling_factor": 100 },
      "category": { "type": "keyword" },
      "tags": { "type": "keyword" },
      "location": { "type": "geo_point" },
      "created_at": { "type": "date" },
      "metadata": {
        "type": "object",
        "enabled": false
      }
    }
  },
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1,
    "analysis": {
      "analyzer": {
        "autocomplete_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": ["lowercase", "autocomplete_filter"]
        }
      },
      "filter": {
        "autocomplete_filter": {
          "type": "edge_ngram",
          "min_gram": 2,
          "max_gram": 20
        }
      }
    }
  }
}
```

## Query Patterns

```typescript
import { Client } from '@elastic/elasticsearch'

const client = new Client({ node: process.env.ELASTICSEARCH_URL })

// Full-text search with boosting and highlighting
async function searchProducts(query: string, filters: ProductFilters) {
  const result = await client.search({
    index: 'products',
    body: {
      query: {
        bool: {
          must: [
            {
              multi_match: {
                query,
                fields: ['title^3', 'description', 'tags^2'],  // Title 3x boost
                type: 'best_fields',
                fuzziness: 'AUTO',         // Typo tolerance
                prefix_length: 2,          // First 2 chars must match exactly
              }
            }
          ],
          filter: [
            ...(filters.category ? [{ term: { category: filters.category } }] : []),
            ...(filters.minPrice || filters.maxPrice ? [{
              range: {
                price: {
                  ...(filters.minPrice && { gte: filters.minPrice }),
                  ...(filters.maxPrice && { lte: filters.maxPrice }),
                }
              }
            }] : []),
            ...(filters.tags?.length ? [{ terms: { tags: filters.tags } }] : []),
          ],
        }
      },
      highlight: {
        fields: {
          title: { number_of_fragments: 0 },       // Full field highlight
          description: { fragment_size: 150 },      // Snippet
        },
        pre_tags: ['<mark>'],
        post_tags: ['</mark>'],
      },
      sort: [
        { _score: 'desc' },
        { created_at: 'desc' },
      ],
      from: filters.offset ?? 0,
      size: filters.limit ?? 20,
    }
  })

  return {
    hits: result.hits.hits.map(hit => ({
      ...hit._source,
      score: hit._score,
      highlights: hit.highlight,
    })),
    total: (result.hits.total as { value: number }).value,
  }
}

// Autocomplete search (edge_ngram)
async function autocomplete(prefix: string) {
  const result = await client.search({
    index: 'products',
    body: {
      query: {
        match: {
          'title.autocomplete': {
            query: prefix,
            operator: 'and',
          }
        }
      },
      _source: ['title', 'category'],
      size: 10,
    }
  })
  return result.hits.hits.map(h => h._source)
}
```

## Aggregation Patterns

```typescript
// Faceted search: get filter counts alongside results
async function searchWithFacets(query: string) {
  const result = await client.search({
    index: 'products',
    body: {
      query: { match: { title: query } },
      size: 20,
      aggs: {
        // Category facets
        categories: {
          terms: { field: 'category', size: 20 }
        },
        // Price ranges
        price_ranges: {
          range: {
            field: 'price',
            ranges: [
              { key: 'budget', to: 50 },
              { key: 'mid', from: 50, to: 200 },
              { key: 'premium', from: 200 },
            ]
          }
        },
        // Price statistics
        price_stats: {
          stats: { field: 'price' }
        },
        // Date histogram
        created_over_time: {
          date_histogram: {
            field: 'created_at',
            calendar_interval: 'month',
          }
        },
      }
    }
  })

  return {
    hits: result.hits.hits,
    facets: {
      categories: result.aggregations?.categories,
      priceRanges: result.aggregations?.price_ranges,
      priceStats: result.aggregations?.price_stats,
      timeline: result.aggregations?.created_over_time,
    }
  }
}
```

## Index Lifecycle Management (ILM)

```json
{
  "policy": {
    "phases": {
      "hot": {
        "min_age": "0ms",
        "actions": {
          "rollover": {
            "max_primary_shard_size": "50gb",
            "max_age": "7d"
          },
          "set_priority": { "priority": 100 }
        }
      },
      "warm": {
        "min_age": "30d",
        "actions": {
          "shrink": { "number_of_shards": 1 },
          "forcemerge": { "max_num_segments": 1 },
          "set_priority": { "priority": 50 },
          "allocate": {
            "number_of_replicas": 0,
            "require": { "data": "warm" }
          }
        }
      },
      "cold": {
        "min_age": "90d",
        "actions": {
          "set_priority": { "priority": 0 },
          "freeze": {},
          "allocate": {
            "require": { "data": "cold" }
          }
        }
      },
      "delete": {
        "min_age": "365d",
        "actions": {
          "delete": {}
        }
      }
    }
  }
}
```

## Bulk Indexing

```typescript
async function bulkIndex(documents: Product[]): Promise<void> {
  const body = documents.flatMap(doc => [
    { index: { _index: 'products', _id: doc.id } },
    doc,
  ])

  const result = await client.bulk({ body, refresh: false })  // No refresh for throughput

  if (result.errors) {
    const erroredItems = result.items.filter((item: any) => item.index?.error)
    console.error(`Bulk indexing errors: ${erroredItems.length}/${documents.length}`)
    for (const item of erroredItems.slice(0, 5)) {
      console.error(item.index?.error)
    }
  }
}

// Reindex with zero downtime using aliases
async function reindexWithAlias(oldIndex: string, newIndex: string, alias: string) {
  // 1. Create new index with updated mappings
  await client.indices.create({ index: newIndex, body: newMappings })

  // 2. Reindex data
  await client.reindex({
    body: { source: { index: oldIndex }, dest: { index: newIndex } },
    wait_for_completion: true,
  })

  // 3. Atomic alias swap
  await client.indices.updateAliases({
    body: {
      actions: [
        { remove: { index: oldIndex, alias } },
        { add: { index: newIndex, alias } },
      ]
    }
  })
}
```

## Checklist

- [ ] Explicit mappings with `dynamic: strict` (no surprise field types)
- [ ] Multi-field mappings: keyword for filtering, text for search
- [ ] Edge n-gram analyzer for autocomplete fields
- [ ] Boost important fields in multi_match (title > description)
- [ ] Use filter context for non-scoring queries (cacheable, faster)
- [ ] ILM policy for hot/warm/cold/delete lifecycle
- [ ] Alias-based indexing for zero-downtime reindexing
- [ ] Bulk API for batch writes (never single-document in loops)

## Anti-Patterns

- Dynamic mapping in production: unexpected field types cause search failures
- Searching keyword fields with full-text queries (no tokenization)
- Refreshing after every write: kills indexing throughput
- Single huge index instead of time-based indices with ILM
- Deep pagination with from/size beyond 10,000 (use search_after)
- Storing data only in ES without a source-of-truth database

Attribution

vibeevalvibeeval
View sourceSee grades on GitHubMore from vibeeval →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Terse caveman voice: answer first, fluff gone, every technical fact kept. Use for /caveman, "caveman mode", "talk like caveman", "be brief", "less tokens". Stays on until "stop caveman" or "normal mode".

1100021 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

698461 votes

Writing Skills

Create and manage Claude Code skills in HASH repository following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns), UserPromptSubmit hook, and the 500-line rule. Includes validation and debugging with SKILL_DEBUG. Examples include rust-error-stack, cargo-dep...

3931 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3421 votes

catchup

Recovers the conversation and failed tool calls of a previous Codex, Amp, Claude Code, Antigravity, Cline, Copilot CLI, Cursor, DeepSeek Harness, Grok Build, Kimi, OpenCode, Pi Agent, or ZCode session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", asks to recover/summarize a previous session before continuing, or asks to diagnose or report a catchup failure. Do NOT use for the current conversation, git history, or any non-agent log.

741 votes
View all in ai-agents →