Elasticsearch 高级技巧
1. 优化查询
使用过滤器(Filter)而不是查询(Query)
Elasticsearch 中的查询分为两种主要类型:查询(Query) 和 过滤器(Filter)。查询会计算文档的相关性分数(_score),而过滤器则不会。因此,使用过滤器可以显著提高查询性能,特别是当你只需要判断文档是否匹配条件而不关心相关性时。
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } }
],
"filter": [
{ "term": { "status": "published" } },
{ "range": { "date": { "gte": "2023-01-01", "lte": "2023-12-31" } } }
]
}
}
}
在这个例子中,match 查询用于全文搜索标题,而 term 和 range 过滤器用于精确匹配状态和日期范围。
利用缓存
Elasticsearch 默认会对过滤器的结果进行缓存,以便后续请求可以直接使用缓存结果,从而减少重复计算。确保频繁使用的过滤器能够充分利用缓存机制。
{
"query": {
"bool": {
"must": [
{ "match": { "content": "performance optimization" } }
],
"filter": [
{ "terms": { "tags": ["elasticsearch", "optimization"] } }
]
}
}
}
在这个例子中,terms 过滤器将被缓存,因为它是基于精确匹配的。
使用复合查询(Compound Queries)
复合查询允许你组合多个简单的查询或过滤器,以实现复杂的逻辑。常见的复合查询包括 bool、dis_max、constant_score 等。
示例:bool 查询
{
"query": {
"bool": {
"should": [
{ "match": { "title": "Elasticsearch" } },
{ "match": { "description": "Elasticsearch" } }
],
"must_not": [
{ "match": { "status": "draft" } }
],


1086

被折叠的 条评论
为什么被折叠?



