darnitdiy
darnitdiy

Reputation: 559

how to add filters to elastic query when using function_score?

Here is my current elastic query:

{
    "from": 0,
    "size": 10,
    "query": {
        "function_score": {
            "query": {
                "bool": {
                    "must": [{
                        "multi_match": {
                            "query": "ocean",
                            "fields": [],
                            "fuzziness": "AUTO"
                        }}],
                    "must_not": [{
                        "exists": {
                            "field": "parentId"
                        }
                    }]
                }
            },
            "functions" : [
                {
                    "gauss": {
                            "createTime": {
                                    "origin": "2020-07-09T23:50:00",
                                    "scale": "365d",
                                    "decay": 0.3
                            }
                    }
                }
            ]
        }
    }
}

How do I properly add filters to this? I think maybe the fact that I'm using function_score makes this different? I would like to add a hard filter, for example, only show me results with uploadUser: 'Mr. Bean' ... but still keep the scoring in place for the results that pass this filter.

I tried using filter in various places, also using must but I either get no results or all the results.

I'm using Elastic Search 7. Thanks for your help

Upvotes: 0

Views: 88

Answers (1)

Bhavya
Bhavya

Reputation: 16172

You can try this below search query:

Refer this ES official documentation to know more about Function score query

    {
  "from": 0,
  "size": 10,
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "filter": {
            "term": {
              "uploadUser": "Mr. Bean"
            }
          },
          "must": [
            {
              "multi_match": {
                "query": "ocean",
                "fields": [
                  
                ],
                "fuzziness": "AUTO"
              }
            }
          ],
          "must_not": [
            {
              "exists": {
                "field": "parentId"
              }
            }
          ]
        }
      },
      "functions": [
        {
          "gauss": {
            "createTime": {
              "origin": "2020-07-09T23:50:00",
              "scale": "365d",
              "decay": 0.3
            }
          }
        }
      ]
    }
  }
}

Upvotes: 2

Related Questions