简体   繁体   中英

Default value for Elasticsearch query

I am doing a project with flask and Elasticsearch. The user passes through the url the query parameters for elasticsearch to perform the search. 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. The solution I implemented would be to check with ifs if the values are filled and to make a different query for each 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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