Elasticsearch模式
Mattakushi4322026-10-25查看 873复制 61
何时激活:Elasticsearch、ES、OpenSearch、全文搜索、映射、分析器、聚合、Kibana
📘如何使用这个技能
- 1复制技能内容·点击上方「Copy SKILL.md」复制全部内容,或 Download 下载到本地
- 2打开你的 AI 客户端·支持 Claude Code、Trae、Cursor、ChatGPT、DeepSeek、Kimi 等任意 AI 助手
- 3粘贴为系统提示/知识文件·Claude Code:放入 .claude/skills/ 目录;普通对话:作为首条消息发送并说「请严格按这份技能文档执行」
- 4直接提出你的需求·AI 会按技能定义的工作流、格式和约束来处理,无需再解释背景
💡 提示:技能生效后,每次对话只需一句需求,AI 会按 SKILL.md 的流程执行。
SKILL.md4218 chars
---
name: elasticsearch-patterns
description: "When to activate: Elasticsearch, ES, OpenSearch, full-text search, mappings, analyzers, aggregations, Kibana"
origin: zakr
metadata:
namespace: zakr/devtools-pack
version: 1.0.0
category: databases
language: sql
platforms: [claude-code, codex, gemini-cli, cursor, aider, windsurf]
---
# Elasticsearch Patterns
## Mappings and Analyzers
```json
PUT /articles
{
"settings": {
"analysis": {
"analyzer": {
"custom_english": {
"type": "custom",
"tokenizer": "standard",
"filter": ["lowercase", "stop", "snowball"]
}
}
}
},
"mappings": {
"properties": {
"title": { "type": "text", "analyzer": "custom_english", "fields": { "keyword": { "type": "keyword" } } },
"body": { "type": "text", "analyzer": "custom_english" },
"tags": { "type": "keyword" },
"price": { "type": "double" },
"created": { "type": "date" },
"author": { "type": "object", "properties": { "id": { "type": "keyword" }, "name": { "type": "text" } } }
}
}
}
```
## Query DSL
```json
// Bool query — the workhorse
GET /articles/_search
{
"query": {
"bool": {
"must": [{ "match": { "title": "elasticsearch patterns" } }],
"filter": [{ "term": { "tags": "backend" } }, { "range": { "created": { "gte": "2024-01-01" } } }],
"should": [{ "match": { "body": "performance" } }],
"must_not": [{ "term": { "status": "draft" } }]
}
},
"highlight": { "fields": { "title": {}, "body": {} } },
"_source": ["title", "tags", "author"],
"from": 0, "size": 20
}
```
```json
// Nested query (for nested objects)
GET /orders/_search
{
"query": {
"nested": {
"path": "items",
"query": { "bool": {
"must": [
{ "match": { "items.name": "laptop" } },
{ "range": { "items.price": { "gte": 500 } } }
]
}}
}
}
}
```
## Aggregations
```json
GET /orders/_search
{
"size": 0,
"aggs": {
"by_status": {
"terms": { "field": "status", "size": 10 },
"aggs": {
"total_revenue": { "sum": { "field": "amount" } },
"avg_amount": { "avg": { "field": "amount" } }
}
},
"revenue_over_time": {
"date_histogram": { "field": "created", "calendar_interval": "month" },
"aggs": { "revenue": { "sum": { "field": "amount" } } }
},
"price_percentiles": {
"percentiles": { "field": "amount", "percents": [50, 75, 90, 99] }
}
}
}
```
## Index Lifecycle Management
```json
PUT /_ilm/policy/logs-policy
{
"policy": {
"phases": {
"hot": { "actions": { "rollover": { "max_size": "50gb", "max_age": "1d" } } },
"warm": { "min_age": "7d", "actions": { "shrink": { "number_of_shards": 1 }, "forcemerge": { "max_num_segments": 1 } } },
"cold": { "min_age": "30d", "actions": { "freeze": {} } },
"delete": { "min_age": "90d", "actions": { "delete": {} } }
}
}
}
```
## Python Client
```python
from elasticsearch import Elasticsearch, helpers
es = Elasticsearch("https://localhost:9200", api_key="key")
# Bulk indexing
def bulk_index(docs):
actions = [
{"_index": "articles", "_id": d["id"], "_source": d}
for d in docs
]
helpers.bulk(es, actions, chunk_size=500, request_timeout=60)
# Search with pagination (search_after for deep pagination)
resp = es.search(index="articles", body={
"query": { "match_all": {} },
"sort": [{ "created": "desc" }, { "_id": "asc" }],
"size": 100
})
last_sort = resp["hits"]["hits"][-1]["sort"]
# Next page:
resp = es.search(index="articles", body={
"query": { "match_all": {} },
"sort": [{ "created": "desc" }, { "_id": "asc" }],
"search_after": last_sort,
"size": 100
})
```
## Performance Tuning
- Shards: 1 shard per 20-40GB; avoid over-sharding
- `refresh_interval: 30s` during bulk indexing (set back to `1s` after)
- `number_of_replicas: 0` during initial load, restore after
- Use `filter` (cached) over `query` (scored) when relevance not needed
- Avoid `wildcard` queries on `text` fields — use n-gram analyzer instead
- Monitor: `_cat/indices`, `_nodes/stats`, `_cluster/health`