Skip to main content
 首页 » 编程设计

python之紧固查询elasticsearch

2025年02月15日7jyk

我正在尝试在 elasticsearch 上进行查询,但令我惊讶的是响应速度非常慢。

request = { 
            "query": { 
                "bool": { 
                    "must": [{"match": {"user.id": self.id}}] 
                } 
            }, 
            "sort": [ 
                {"created_at": {"order": "asc"}} 
            ] 
        } 

查询需要三秒半 (3.5s) 才能得到响应。我在本地工作,所以问题不可能来自网络问题。

知道查询命中了包含 4000 万个文档的索引,我该如何提高查询速度?

请您参考如下方法:

假设您使用的是默认设置,您使用的是标准分析器

match query在实际查询之前,将对搜索词应用相同的标准分析器。它还会计算匹配文档的分数,这也会对查询性能产生一定的影响。

term query不会对搜索词应用任何分析器,因此只会在倒排索引中查找确切的词。

现在,是否计算得分取决于 query-filter-context

查询上下文

A query clause used in query context answers the question “How well does this document match this query clause?” Besides deciding whether or not the document matches, the query clause also calculates a _score representing how well the document matches, relative to other documents.

过滤上下文

In filter context, a query clause answers the question “Does this document match this query clause?” The answer is a simple Yes or No — no scores are calculated.

Frequently used filters will be cached automatically by Elasticsearch, to speed up performance.

您可以按如下所述创建查询:

GET _search 
{ 
  "query": {  
    "bool": { 
      "must": [ 
        { "match_all": {}} 
      ], 
      "filter": [  
        { "term":  { "user.id": <YOUR_ID_PARAM> }},  
      ] 
    }, 
    "sort" :{.....} 
  } 
}