elasticsearchmustacheis-emptyelasticsearch-queryelasticsearch-template

How to get all documents from a filter in Elasticsearch?


If I deliver the empty params (see below) I would like to get all documents from Elasticsearch. How can I achieve this?

One solution is that I could write all the existing categories into an array. But I have more than 100 categories and this will not be a good solution.

Can someone please help me? Is it possible to ignore the terms if the array is empty?

POST _scripts/test{"script": {
"lang": "mustache",
"source": {
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "terms": {
          "category": [
            "{{#category}}",
            "{{.}}",
            "{{/category}}"
          ]}}}}}}}

If I execute the below query the results will be empty:

GET poi/_search/template{
"id": "test", 
"params": {
    "category" : [""]
}}

Solution

  • The best way to achieve this would be to proceed like this with a JSON array:

    POST _scripts/test
    {
      "script": {
        "lang": "mustache",
        "source": """
        {
          "query": {
            "bool": {
              "must": {
                "match_all": {}
              },
              "filter": [
                {{#category}}
                {
                  "terms": {
                    "category": {{#toJson}}category.values{{/toJson}}
                  }
                }
                {{/category}}
              ]
            }
          }
        }
        """
      }
    }
    

    Then you can execute this search template like this:

    GET poi/_search/template
    {
      "id": "test", 
      "params": {
        "category" : {
          "values": ["cat1", "cat2", "cat3"]
        }
      }
    }
    

    And if you don't want to specify any categories, like this:

    GET poi/_search/template
    {
      "id": "test", 
      "params": {
      }
    }