Search code examples
elasticsearchkibananestelasticsearch-marvel

ElasticSearch should/must clause not working as expected


Below is my elastic query

 GET _search
{
  "query": {
    "bool": {
      "must": {
        "match": {
          "marriages.marriage_year": "1630"
        }
      },
      "should": {
        "match": {
          "first_name": {
            "query": "mary",
            "fuzziness": "2"
          }
        }
      },
      "must": {
        "range": {
          "marriages.marriage_year": {
            "gt": "1620",
            "lte": "1740"
          }
        }
      }
    }
  }
}

It is returning data with marriages.marriage_year= "1630" with Mary as first_name as highest score.I also want to include marriages.marriage_year between 1620 - 1740 which are not shown in the results. It is showing data only for marriage_year 1630


Solution

  • That's because you have two bool/must clauses and the second one gets eliminated when the JSON query is parsed. Rewrite it like this instead and it will work:

    {
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "marriages.marriage_year": "1630"
              }
            },
            {
              "range": {
                "marriages.marriage_year": {
                  "gt": "1620",
                  "lte": "1740"
                }
              }
            }
          ],
          "should": {
            "match": {
              "first_name": {
                "query": "mary",
                "fuzziness": "2"
              }
            }
          }
        }
      }
    }
    

    UPDATE

    Then you need to do it differently and in the bool/must you need to have only the range query and move the match inside the bool/should section:

    {
      "query": {
        "bool": {
          "must": [
            {
              "range": {
                "marriages.marriage_year": {
                  "gt": "1620",
                  "lte": "1740"
                }
              }
            }
          ],
          "should": [
            {
              "match": {
                "first_name": {
                  "query": "mary",
                  "fuzziness": "2"
                }
              }
            },
            {
              "match": {
                "marriages.marriage_year": "1630"
              }
            }
          ]
        }
      }
    }