Elasticsearch 集成:自定义分析器与同义词搜索
不止是简单 haystack 集成,直接在 ES 层面配置领域同义词提升搜索准确性。 · 难度:入门 · +10XP
Elasticsearch 集成:自定义分析器与同义词搜索
普通教程仅会用 django-elasticsearch-dsl 做基础全文检索。本课教你如何在索引映射中定义自定义分析器,包括同义词过滤(synonym token filter)和停用词。你将编写 DSL 模板,通过信号自动更新索引,并测试 '手机' 同时匹配 '手机'、'移动电话'、'mobile' 等场景,让搜索结果更贴近业务。
# search_indexes.py
from django_elasticsearch_dsl import Index, Document
from myapp.models import Product
products = Index('products')
products.settings(
analysis={
'filter': {
'my_synonym': {
'type': 'synonym',
'synonyms': [
'手机, 移动电话, mobile',
'电脑, 计算机, computer'
]
}
},
'analyzer': {
'my_analyzer': {
'type': 'custom',
'tokenizer': 'standard',
'filter': ['lowercase', 'my_synonym']
}
}
}
)
@products.doc_type
class ProductDocument(Document):
class Django:
model = Product
fields = ['name', 'description']
def get_queryset(self):
return super().get_queryset().select_related('category')