簡體   English   中英

Elasticsearch 查詢的默認值

[英]Default value for Elasticsearch query

我正在用 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 查詢可以通過 go 的所有標題值。 我實施的解決方案是使用ifs檢查值是否已填充,並為每個 if 進行不同的查詢。 但是當我為查詢實現更多參數時,代碼變得非常大。

解決此問題的一種方法是聲明一個最低限度的查詢並根據您收到的輸入參數填充它。 例如,

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

您現在可以執行文檔查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM