Search code examples
elasticsearchelasticsearch-dsl

What's the most efficient way to filter out items with member that don't contain the terms?


What's the most efficient way to write the following query?

Get 5 items that have member member that contains any of these items: ['item1', 'item2'].

should: [{ terms : {member: ['item1', 'item2'] } }]

If you find only 3 items, get 2 more where member is empty.

How do I finish this query?


Solution

  • You can use a should clause with term and not exists. So it will fetch documents where field member matches input query and where field doesn't exist. You can pass size to get top 5 documents from result

    {
      "size": 5,
      "query": {
        "bool": {
          "should": [
            {
              "terms": {
                "member": [
                  "1",
                  "2",
                  "3"
                ]
              }
            },
            {
              "bool": {
                "must_not": [
                  {
                    "exists": {
                      "field": "member"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }