Search code examples
elasticsearchkibanaelastic-stack

How do i combine different search parameters in an elasticscearch dsl query?


Good day together,

I have a little problem in Elastic/Kibana. In the Kibana Query Language "KQL" it is possible for me to execute a certain query:

car:* AND coun: * AND doc: (bes* OR *rvr*) AND NOT coun: (SIP OR LUK)

I would like to use this as a filter query using Elasticscearch query DSL. Only I don't get the same result. For this I use the boolean operator. My query looks like this:

{
  "query": {
    "bool": {
      "must": [
        {
          "exists": {
            "field": "car"
          }
        },
        {
          "exists": {
            "field": "coun"
          }
        }
      ],
      "should": [
        {
          "wildcard": {
            "doc.keyword": {
              "value": "bes*"
            }
          }
        },
        {
          "wildcard": {
            "doc.keyword": {
              "value": "*rvr*"
            }
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "coun.keyword": "SIP"
          }
        },
        {
          "term": {
            "coun.keyword": "LUK"
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

Unfortunately, I do not get the same result. My guess is the "should" operator. But I don't know exactly how to adjust the code.

I would be very grateful for any answer! Thanks a lot!


Solution

  • Problem here, that you putting OR outside AND. Just move should clause inside must. Like this

    GET _search
    {
      "query": {
        "bool": {
          "must": [
            {
              "exists": {
                "field": "car"
              }
            },
            {
              "exists": {
                "field": "con"
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "wildcard": {
                      "doc.keyword": {
                        "value": "bes*"
                      }
                    }
                  },
                  {
                    "wildcard": {
                      "doc.keyword": {
                        "value": "*rvr*"
                      }
                    }
                  }
                ]
              }
            }
          ],
          "must_not": [
            {
              "term": {
                "coun.keyword": "SIP"
              }
            },
            {
              "term": {
                "coun.keyword": "LUK"
              }
            }
          ],
          "minimum_should_match": 1
        }
      }
    }