Home > Software design >  ElasticSearch "A" or "empty"
ElasticSearch "A" or "empty"

Time:11-19

I have the following index index

{
  "docs": {
    "mappings": {
      "text": {
        "properties": {
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
          "code": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    }
  }
}

"code" can have values: ["a"], ["b"],["a","b"], or []

I need a query to relieve values with code: "a" or []. Can anyone help with this query, here is what I have tried so far w/out success (this appears to say "a" AND "[]"; I want "a" OR "[]").

"bool": {
  "should": [
    {
      "match": {
        "code": "a"
      }
    }
  ],
  "must_not": [
    {
      "exists": {
        "field": "code"
      }
    }
  ]
}
  

CodePudding user response:

OR can be achieved with bool/should, but the bool/must constraint must be inside the bool/should.

You should try with this query:

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "match": {
            "code": "a"
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "code"
                }
              }
            ]
          }
        }
      ]
    }
  }
}
  • Related