mcpField
E
elasticsearch-best-practices

elasticsearch-best-practices

github.com/mindrallyデータ・データベース2871.0k 回インストール3 週間前に更新
リポジトリ

elasticsearch-best-practices について

Elasticsearch の利用者向けに、インデックス設計と検索運用の指針をまとめたスキルです。マッピング、シャード、クエリ、監視、セキュリティを扱います。

主な機能

  1. 01マッピングとフィールド型の指針
  2. 02シャード設計とライフサイクル管理
  3. 03クエリと集計の最適化
  4. 04バルクインデックスと分析
  5. 05性能監視とアクセス制御

活用シーン

  1. 01新規インデックスのマッピング設計
  2. 02検索と集計のチューニング
  3. 03バルクインデックス処理の管理
  4. 04クラスタ状態とアクセス制御の確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mindrally/skills --skill elasticsearch-best-practices

インストール後、Claude Code で/elasticsearch-best-practicesを入力して読み込まれたか確認します。

詳細

Elasticsearch のベストプラクティス

基本原則

  • クエリパターンに基づいてインデックスとマッピングを設計します
  • 適切な解析とインデックス作成により、検索パフォーマンスを最適化します
  • 適切なシャードサイズとクラスター構成を使用します
  • 適切なセキュリティとアクセス制御を実装します
  • クラスターの健全性を監視し、クエリを最適化します

インデックス設計

マッピングのベストプラクティス
  • 動的マッピングに頼らず、明示的なマッピングを定義します
  • 各フィールドに適切なデータ型を使用します
  • 検索しないフィールドのインデックス作成を無効にします
  • 完全一致には keyword 型、全文検索には text 型を使用します
{
  "mappings": {
    "properties": {
      "product_id": {
        "type": "keyword"
      },
      "name": {
        "type": "text",
        "analyzer": "standard",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "description": {
        "type": "text",
        "analyzer": "english"
      },
      "price": {
        "type": "scaled_float",
        "scaling_factor": 100
      },
      "category": {
        "type": "keyword"
      },
      "tags": {
        "type": "keyword"
      },
      "created_at": {
        "type": "date"
      },
      "metadata": {
        "type": "object",
        "enabled": false
      },
      "location": {
        "type": "geo_point"
      }
    }
  }
}
フィールド型
  • keyword:完全一致する値、フィルタリング、集計、ソート
  • text:解析を伴う全文検索
  • date:形式を指定した日付/時刻の値
  • numeric types:long、integer、short、byte、double、float、scaled_float
  • boolean:真偽値
  • geo_point:緯度/経度のペア
  • nested:個別にクエリする必要があるオブジェクトの配列
インデックス設定
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1,
    "refresh_interval": "30s",
    "analysis": {
      "analyzer": {
        "custom_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": ["lowercase", "asciifolding", "synonym_filter"]
        }
      },
      "filter": {
        "synonym_filter": {
          "type": "synonym",
          "synonyms": ["laptop, notebook", "phone, mobile, smartphone"]
        }
      }
    }
  }
}

シャードサイズ

ガイドライン
  • シャードあたり20~40GBを目標にします
  • ヒープ1GBあたり約20シャードを目安にします
  • 過剰なシャーディング(小さなシャードが多すぎる状態)を避けます
  • 時系列データには、時間ベースのインデックスを検討します
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  }
}
インデックスライフサイクル管理(ILM)
{
  "policy": {
    "phases": {
      "hot": {
        "min_age": "0ms",
        "actions": {
          "rollover": {
            "max_size": "50gb",
            "max_age": "7d"
          }
        }
      },
      "warm": {
        "min_age": "30d",
        "actions": {
          "shrink": {
            "number_of_shards": 1
          },
          "forcemerge": {
            "max_num_segments": 1
          }
        }
      },
      "delete": {
        "min_age": "90d",
        "actions": {
          "delete": {}
        }
      }
    }
  }
}

クエリの最適化

クエリの種類
Match クエリ(全文検索)
{
  "query": {
    "match": {
      "description": {
        "query": "wireless bluetooth headphones",
        "operator": "and",
        "fuzziness": "AUTO"
      }
    }
  }
}
Term クエリ(完全一致)
{
  "query": {
    "term": {
      "status": "active"
    }
  }
}
Bool クエリ(クエリの組み合わせ)
{
  "query": {
    "bool": {
      "must": [
        { "match": { "name": "laptop" } }
      ],
      "filter": [
        { "term": { "category": "electronics" } },
        { "range": { "price": { "gte": 500, "lte": 2000 } } }
      ],
      "should": [
        { "term": { "brand": "apple" } }
      ],
      "must_not": [
        { "term": { "status": "discontinued" } }
      ]
    }
  }
}
クエリのベストプラクティス
  • スコアリングを行わないクエリには filter コンテキストを使用します(キャッシュ可能)
  • スコアリングが必要な場合にのみ must を使用します
  • 用語の先頭でワイルドカードを使うのは避けます
  • 完全一致には keyword フィールドを使用します
  • size パラメーターで結果数を制限します
{
  "query": {
    "bool": {
      "must": {
        "multi_match": {
          "query": "search terms",
          "fields": ["name^3", "description", "tags^2"],
          "type": "best_fields"
        }
      },
      "filter": [
        { "term": { "active": true } },
        { "range": { "created_at": { "gte": "now-30d" } } }
      ]
    }
  },
  "size": 20,
  "from": 0,
  "_source": ["name", "price", "category"]
}

集計

一般的な集計パターン
{
  "size": 0,
  "aggs": {
    "categories": {
      "terms": {
        "field": "category",
        "size": 10
      },
      "aggs": {
        "avg_price": {
          "avg": { "field": "price" }
        }
      }
    },
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 100 },
          { "from": 100, "to": 500 },
          { "from": 500 }
        ]
      }
    },
    "date_histogram": {
      "date_histogram": {
        "field": "created_at",
        "calendar_interval": "month"
      }
    }
  }
}
集計のベストプラクティス
  • 集計のみが必要な場合は size: 0 を使用します
  • terms 集計には適切な shard_size を設定します
  • ページネーションには複合集計を使用します
  • 対象範囲を絞り込むため、aggs フィルターの使用を検討します

インデックス作成のベストプラクティス

バルクインデックス作成
POST _bulk
{ "index": { "_index": "products", "_id": "1" } }
{ "name": "Product 1", "price": 99.99 }
{ "index": { "_index": "products", "_id": "2" } }
{ "name": "Product 2", "price": 149.99 }
Bulk API のガイドライン
  • バッチ操作には Bulk API を使用します
  • 最適なバルクサイズはリクエストあたり5~15MBです
  • リクエストの拒否(スレッドプールのキューが満杯)を監視します
  • パフォーマンス向上のため、バルクインデックス作成中はリフレッシュを無効にします
PUT /products/_settings
{
  "refresh_interval": "-1"
}

// After bulk indexing:
PUT /products/_settings
{
  "refresh_interval": "1s"
}

POST /products/_refresh
ドキュメントの更新
POST /products/_update/1
{
  "doc": {
    "price": 89.99,
    "updated_at": "2024-01-15T10:30:00Z"
  }
}

// Update by query
POST /products/_update_by_query
{
  "query": {
    "term": { "category": "electronics" }
  },
  "script": {
    "source": "ctx._source.on_sale = true"
  }
}

解析とトークン化

カスタムアナライザー
{
  "settings": {
    "analysis": {
      "analyzer": {
        "product_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "asciifolding",
            "english_stop",
            "english_stemmer"
          ]
        },
        "autocomplete_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "edge_ngram_filter"
          ]
        }
      },
      "filter": {
        "english_stop": {
          "type": "stop",
          "stopwords": "_english_"
        },
        "english_stemmer": {
          "type": "stemmer",
          "language": "english"
        },
        "edge_ngram_filter": {
          "type": "edge_ngram",
          "min_gram": 2,
          "max_gram": 15
        }
      }
    }
  }
}
アナライザーのテスト
POST /products/_analyze
{
  "analyzer": "product_analyzer",
  "text": "Wireless Bluetooth Headphones"
}

検索機能

オートコンプリート/サジェスト
{
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "fields": {
          "suggest": {
            "type": "completion"
          }
        }
      }
    }
  }
}

// Query suggestions
{
  "suggest": {
    "product-suggest": {
      "prefix": "wire",
      "completion": {
        "field": "name.suggest",
        "size": 5
      }
    }
  }
}
ハイライト表示
{
  "query": {
    "match": { "description": "wireless" }
  },
  "highlight": {
    "fields": {
      "description": {
        "pre_tags": ["<em>"],
        "post_tags": ["</em>"],
        "fragment_size": 150
      }
    }
  }
}

パフォーマンスの最適化

クエリキャッシュ
  • フィルタークエリは自動的にキャッシュされます
  • 頻繁に繰り返される条件には filter コンテキストを使用します
  • キャッシュのヒット率を監視します
検索パフォーマンス
  • 深いページネーションを避けます(代わりに search_after を使用します)
  • 返す _source フィールドを制限します
  • ソートと集計には doc_values を使用します
  • よく使うソート順に合わせてインデックスを事前にソートします
{
  "query": { "match_all": {} },
  "size": 20,
  "search_after": [1705329600000, "product_123"],
  "sort": [
    { "created_at": "desc" },
    { "_id": "asc" }
  ]
}

監視とメンテナンス

クラスターの健全性
GET _cluster/health
GET _cat/indices?v
GET _cat/shards?v
GET _nodes/stats
インデックスのメンテナンス
POST /products/_forcemerge?max_num_segments=1
POST /products/_cache/clear
POST /products/_refresh
スロークエリログ
PUT /products/_settings
{
  "index.search.slowlog.threshold.query.warn": "10s",
  "index.search.slowlog.threshold.query.info": "5s",
  "index.search.slowlog.threshold.fetch.warn": "1s"
}

セキュリティ

インデックスレベルのセキュリティ
PUT _security/role/products_reader
{
  "indices": [
    {
      "names": ["products*"],
      "privileges": ["read"]
    }
  ]
}
フィールドレベルのセキュリティ
PUT _security/role/limited_access
{
  "indices": [
    {
      "names": ["users"],
      "privileges": ["read"],
      "field_security": {
        "grant": ["name", "email", "created_at"]
      }
    }
  ]
}

エイリアスと再インデックス

インデックスエイリアス
POST _aliases
{
  "actions": [
    { "add": { "index": "products_v2", "alias": "products" } },
    { "remove": { "index": "products_v1", "alias": "products" } }
  ]
}
変換を伴う再インデックス
POST _reindex
{
  "source": {
    "index": "products_v1"
  },
  "dest": {
    "index": "products_v2"
  },
  "script": {
    "source": "ctx._source.migrated_at = new Date().toString()"
  }
}

コメント