ElasticSearch 全文搜索优化:从分词器到相关性调优

Mei Lin | 2026-08-26T23:02:35 | Database

深入讲解 ES 中文分词配置、索引设计、bool 查询组合以及 function_score 相关性调优技巧。

# ElasticSearch 全文搜索优化 ## 中文分词器选型 | 分词器 | 特点 | 适用场景 | |--------|------|---------| | Standard | 单字切分 | 不适合中文 | | IK (ik_max_word) | 最细粒度切分 | 搜索场景 | | IK (ik_smart) | 最粗粒度切分 | 索引场景 | | jieba | 支持新词发现 | 自然语言处理 | ## 索引设计 ```json { "settings": { "analysis": { "analyzer": { "ik_pinyin": { "type": "custom", "tokenizer": "ik_max_word", "filter": ["pinyin_filter", "lowercase"] } }, "filter": { "pinyin_filter": { "type": "pinyin", "keep_full_pinyin": true, "keep_original": true } } } }, "mappings": { "properties": { "title": { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart", "fields": { "pinyin": { "type": "text", "analyzer": "ik_pinyin" } } }, "content": { "type": "text", "analyzer": "ik_max_word" } } } } ``` ## Bool 查询组合 ```json { "query": { "bool": { "must": [ { "multi_match": { "query": "Spring Boot 微服务", "fields": ["title^3", "content", "title.pinyin"], "type": "best_fields" } } ], "filter": [ { "term": { "status": "published" } }, { "range": { "created_at": { "gte": "2024-01-01" } } } ], "should": [ { "term": { "is_featured": true } } ] } } } ``` `title^3` 表示标题匹配的权重是正文的 3 倍。 ## function_score 相关性调优 ```json { "query": { "function_score": { "query": { "match": { "title": "Java 并发" } }, "functions": [ { "field_value_factor": { "field": "view_count", "modifier": "log1p", "factor": 0.1 } }, { "gauss": { "created_at": { "origin": "now", "scale": "30d", "decay": 0.5 } } } ], "score_mode": "sum", "boost_mode": "multiply" } } } ``` 综合考虑文本相关性、浏览量和时效性。 ## 性能优化 1. 禁用不需要搜索的字段 `"index": false` 2. 合理设置分片数(每个分片 10-50GB) 3. 使用 `_source` filtering 减少返回数据 4. 频繁聚合的字段用 `keyword` 类型

← Back to Blog