elasticsearchnestelasticsearch-netelasticsearch-5

Multiple should queries with must query


I am building a query to Elastic 5 (using nest in .net), i am trying to achive this result:

Must have value1 and value 2

Should have value3 or value 4

and should have value5 or value6

Here is my query:

    {
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "code": {
              "query": "value1"
            }
          }
        },
        {
          "match": {
            "code": {
              "query": "value2"
            }
          }
        }
      ],
      "should": [
        {
          "match": {
            "code": {
              "query": "value3"
            }
          }
        },
        {
          "match": {
            "code": {
              "query": "value4"
            }
          }
        }
        ],
        "should": [
        {
          "match": {
            "code": {
              "query": "value5"
            }
          }
        },
        {
          "match": {
            "code": {
              "query": "value6"
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

I dont get the desired answer (for example i dont have anywhere value 5 and value 6 but still getting results)

Thank you


Solution

  • Then you need something like this:

    {
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "code": {
                  "query": "value1"
                }
              }
            },
            {
              "match": {
                "code": {
                  "query": "value2"
                }
              }
            },
            {
              "bool": {
                "minimum_should_match": 1,
                "should": [
                  {
                    "match": {
                      "code": {
                        "query": "value3"
                      }
                    }
                  },
                  {
                    "match": {
                      "code": {
                        "query": "value4"
                      }
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "minimum_should_match": 1,
                "should": [
                  {
                    "match": {
                      "code": {
                        "query": "value5"
                      }
                    }
                  },
                  {
                    "match": {
                      "code": {
                        "query": "value6"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }