主题
Elasticsearch 03 · 功能详解
四篇制:01 理论 · 02 部署 · 03 功能 · 04 实战 本篇是 mapping、检索 DSL 与聚合。倒排索引/分词原理见 01 理论。
一、mapping 与字段类型
mapping 定义字段怎么索引。最关键的区别:
- text:会分词,用于全文检索(match)。
- keyword:不分词,整体作为一个 term,用于精确过滤(term)、聚合、排序。
一个字段常两者都要:
json
PUT /products
{
"mappings": {
"properties": {
"title": { "type": "text", "analyzer": "ik_max_word",
"fields": { "raw": { "type": "keyword" } } },
"status": { "type": "keyword" },
"price": { "type": "double" },
"created":{ "type": "date" }
}
}
}title 用 text 分词搜索,title.raw 用 keyword 聚合排序。状态码/ID 这类建成 text 会导致聚合报错(text 默认不能聚合),必须 keyword。
IK 中文分词器
bash
bin/elasticsearch-plugin install https://get.infini.cloud/elasticsearch/analysis-ik/9.5.4ik_max_word 最细粒度切(建索引用,召回多),ik_smart 粗粒度切(搜索用,准确)。装完重启节点。
二、文档 CRUD
bash
# 写入(指定 id 用 PUT,自动生成用 POST)
curl -k -u elastic:密码 -XPOST 'https://10.0.0.61:9200/products/_doc?pretty' \
-H 'Content-Type: application/json' -d '{"title":"运维工程师手册","price":59,"status":"on"}'
# 按 id 查 / 删
curl -k -u elastic:密码 'https://10.0.0.61:9200/products/_doc/ID?pretty'
curl -k -u elastic:密码 -XDELETE 'https://10.0.0.61:9200/products/_doc/ID?pretty'三、Query DSL
match vs term
match:先对查询词分词,再匹配(全文检索)。term:不分词,精确匹配 keyword 字段。
json
GET /products/_search
{ "query": { "match": { "title": "运维工程师" } } }bool 组合
json
{ "query": { "bool": {
"must": [ { "match": { "title": "运维" } } ],
"filter": [ { "term": { "status": "on" } },
{ "range": { "price": { "lte": 100 } } } ],
"must_not": [ { "term": { "status": "off" } } ]
} } }must 算相关性分,filter 不算分且可缓存(精确过滤放 filter 更快),should 或,must_not 非。
四、聚合分析
聚合分两类:bucket(分组,如按 status 分桶)和 metric(统计,如 avg/sum/max)。
json
GET /products/_search
{ "size": 0,
"aggs": {
"by_status": {
"terms": { "field": "status" },
"aggs": { "avg_price": { "avg": { "field": "price" } } }
}
} }size:0 只要聚合结果不要文档。按状态分组并算每组均价——这是 ES 做分析的核心能力。
五、分页方式
| 方式 | 适用 | 限制 |
|---|---|---|
| from + size | 浅分页 | from+size 默认 ≤10000,深分页极慢 |
| search_after | 深分页(推荐) | 需排序字段,无状态 |
| scroll | 全量导出 | 占资源,不适合实时分页 |
深分页用 search_after 带上上一页最后一条的排序值,避免 from 越大越慢。
六、官方文档
- Mapping:https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html
- Query DSL:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html
- 聚合:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
- IK 分词:https://github.com/infinilabs/analysis-ik
黑公网安备23022102000118号