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
  • 每 GB 堆内存约对应 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()"
  }
}

评论

支持 Markdown