简体   繁体   English

Elasticsearch 查询的默认值

[英]Default value for Elasticsearch query

I am doing a project with flask and Elasticsearch.我正在用 flask 和 Elasticsearch 做一个项目。 The user passes through the url the query parameters for elasticsearch to perform the search.用户通过url查询参数elasticsearch进行搜索。 I currently have two fields: Phrase and date.我目前有两个字段:短语和日期。

@app.route('/search')
def get_search_article():

  phrase = request.args.get('phrase')
  from_date = request.args.get('from')
  to_date = request.args.get('to')

doc = {
          "query": {
            "bool": {
              "must": [
                {
                  "match": {
                    "title": phrase
                  }
                }
              ],
              "filter": [
                {
                  "range": {
                    "pubDate": {
                      "gte": from_date + ' 00:00:00',
                      "lte": to_date + ' 23:59:59'
                    }
                  }
                }
              ]
            }
          }
        }

I would like to know if there is a way, if the user does not pass the value, for example of the phrase through the url, the elasticsearch query can go through all the title values.我想知道有没有办法,如果用户不传递值,例如通过 url 的短语,elasticsearch 查询可以通过 go 的所有标题值。 The solution I implemented would be to check with ifs if the values are filled and to make a different query for each if.我实施的解决方案是使用ifs检查值是否已填充,并为每个 if 进行不同的查询。 But as I implement more parameters for the query, the code becomes very large.但是当我为查询实现更多参数时,代码变得非常大。

One way to approach this problem is by declaring a bare-minimum query and populate it according to the input parameters you receive.解决此问题的一种方法是声明一个最低限度的查询并根据您收到的输入参数填充它。 For example,例如,

from_date = request.args.get('from')
to_date = request.args.get('to')

doc = {
          "query": {
            "bool": {
              "must": [

              ],
              "filter": [
                {
                  "range": {
                    "pubDate": {
                      "gte": from_date + ' 00:00:00',
                      "lte": to_date + ' 23:59:59'
                    }
                  }
                }
              ]
            }
          }
        }


phrase = request.args.get('phrase')
if phrase is not None:
    doc['query']['bool']['must'].append(
        {
            "match": {
                "title": phrase
            } 
        }
    ) 

You can execute the doc query now.您现在可以执行文档查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM