Elasticsearch权威指南:common_grams Token Filter解析与应用
概述
在Elasticsearch的文本处理流程中,common_grams
token filter是一个专门优化包含停用词(Stopwords)的短语查询效率的重要组件。本文将深入解析其工作原理、配置方法以及实际应用场景。
核心概念
什么是common_grams
common_grams
token filter通过生成特殊形式的n-gram(特别是bigram)来优化包含常见词(如"the"、"and"等)的短语查询。它与shingles
token filter类似,但针对停用词场景做了特殊优化。
工作原理对比
传统shingles
处理"The quick and brown fox"会生成:
the_quick
quick_and
and_brown
brown_fox
而common_grams
会生成更智能的组合:
the, the_quick
quick, quick_and
and, and_brown
brown
fox
配置详解
双模式配置
common_grams
需要区分索引时和查询时两种模式:
PUT /my_index
{
"settings": {
"analysis": {
"filter": {
"index_filter": {
"type": "common_grams",
"common_words": "_english_"
},
"search_filter": {
"type": "common_grams",
"common_words": "_english_",
"query_mode": true
}
},
"analyzer": {
"index_grams": {
"tokenizer": "standard",
"filter": ["lowercase", "index_filter"]
},
"search_grams": {
"tokenizer": "standard",
"filter": ["lowercase", "search_filter"]
}
}
}
}
}
关键参数说明:
common_words
: 指定常见词列表,支持预设语言(如_english_)或自定义列表query_mode
: 设置为true表示查询时分析器
字段映射配置
PUT /my_index/_mapping/my_type
{
"properties": {
"text": {
"type": "string",
"analyzer": "index_grams",
"search_analyzer": "standard"
}
}
}
工作流程解析
索引时处理
索引阶段,common_grams
会:
- 输出所有原始unigram(单个词)
- 对常见词及其相邻词生成bigram
- 保持位置信息一致
例如"The quick and brown fox"会被处理为:
Pos 1: the, the_quick
Pos 2: quick, quick_and
Pos 3: and, and_brown
Pos 4: brown
Pos 5: fox
查询时优化
普通查询
使用标准分析器时,普通match查询不受影响:
GET /my_index/_search
{
"query": {
"match": {
"text": {
"query": "the quick and brown fox",
"cutoff_frequency": 0.01
}
}
}
}
短语查询优化
使用search_grams
分析器时,会智能转换查询:
GET /my_index/_search
{
"query": {
"match_phrase": {
"text": {
"query": "The quick and brown fox",
"analyzer": "search_grams"
}
}
}
}
转换后的查询词项:
Pos 1: the_quick
Pos 2: quick_and
Pos 3: and_brown
Pos 4: brown
Pos 5: fox
优化效果:
- 减少常见词单独出现的频率
- 大幅降低需要检查的文档数量
- 提升文件系统缓存效率
特殊场景优化
双词短语查询
对于常见双词短语如"The quick":
GET /my_index/_search
{
"query": {
"match_phrase": {
"text": {
"query": "The quick",
"analyzer": "search_grams"
}
}
}
}
search_grams
会将其转换为单个词项the_quick
,实现:
- 将复杂短语查询简化为高效的单词查询
- 显著提升查询性能
最佳实践建议
- 对包含大量常见词的文本字段使用
common_grams
- 区分索引时和查询时分析器配置
- 针对实际查询模式调整常见词列表
- 对主要执行短语查询的字段优先考虑此优化
- 结合
cutoff_frequency
参数实现更智能的常见词处理
通过合理使用common_grams
token filter,可以显著提升包含常见词的短语查询性能,特别是在处理自然语言文本时效果尤为明显。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考