Converting Elastic Search and/or queries to should/should not queries

One of the significant changes in moving from Elastic Search 2 to 5 is the removal of the deprecated ‘and’, and ‘or’ queries from the dsl, replacing them with nested bool must, and should queries. Performing this migration is a developer task, that probably could be automated. In the absence of automation, here are the steps I’ve followed:

  1. replace and: with a nested bool: must:
  2. replace or: with a nested bool: should:

In practice this will take a query that might be something like:

{
  "index": "people",
  "body": {
    "query": {
      "and": [
        {
          "or": [
            {"match": {"first_name": "Fred"}},
            {"match": {"last_name": "Fred"}}
          ]
        },
        {"match": {"last_name": "Fred"}}
      ]
    }
  }
}

and changing it to:

{
  "index": "people",
  "body": {
    "query": {
      "bool": {
        "must": [
          {
            "bool": {
              "should": [
                {"match": {"first_name": "Fred"}},
                {"match": {"last_name": "Fred"}}
              ]
            }
          },
          {"match": {"last_name": "Fred"}}
        ]
      }
    }
  }
}

Personally I like the deprecated and removed 2 syntax, but there is little choice in the matter if you want to upgrade to the latest and greatest elastic, which does include many new good features.

Leave a Reply

Your email address will not be published. Required fields are marked *