PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to get all documents from a filter in Elasticsearch?

 October 28, 2022     elasticsearch, elasticsearch-query, elasticsearch-template, is-empty, mustache     No comments   

Issue

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": {
  }
}


Answered By - Val
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing