Elasticsearch查询的默认值

问题描述 投票:0回答:1

我正在与flask和Elasticsearch进行项目。用户通过URL将查询参数传递给elasticsearch以执行搜索。我目前有两个字段:词组和日期。

@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'
                    }
                  }
                }
              ]
            }
          }
        }

我想知道是否有办法,如果用户不通过URL传递短语等值,elasticsearch查询可以遍历所有标题值。我实现的解决方案是使用ifs检查值是否已填充,并对每个if进行不同的查询。但是随着我为查询实现更多参数,代码变得非常大。

python elasticsearch flask
1个回答
0
投票

解决此问题的一种方法是声明一个最小查询,并根据收到的输入参数填充它。例如,

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
            } 
        }
    ) 

您现在可以执行文档查询。

© www.soinside.com 2019 - 2024. All rights reserved.