Home > other >  Elasticsearch mapping boolean with value "0" and "1"
Elasticsearch mapping boolean with value "0" and "1"

Time:11-04

ElasticSearch version 7.13

Index already exist and I want to reindex with mapping, the field is a boolean. But when I'm trying to reindex, the field has "1" and "0" (string).

How can I evaluate if field = "1" set true (same for 0, but false)?

I have read about runtime, but can't figure out how does it work.

my mapping

{
 mappings:{
  "OPTIONS": {
     "type": "nested",
     "properties":{
        "COMBINABLE": {
          "type": "boolean"
        }
     }
  }
 }
}

and document

{
  "options": [
    {
      "COMBINABLE": "0"
    }
  ]
}

CodePudding user response:

You might consider using pipeline ingestion to convert your number to a boolean value, you can do something like this:

POST _ingest/pipeline/_simulate

{
    "pipeline": {
    "description": "convert to boolean",
    "processors": [
      {
        "script": {
          "source": "def options = ctx.options;def pairs = new ArrayList();for (def pair : options) {def k = false;if (pair[\"COMBINABLE\"] == \"1\" || pair[\"COMBINABLE\"] == 1) {k = true;}pair[\"COMBINABLE\"] = k;}ctx.options = options;"
        }
      }
    ]
  },
    "docs": [
        {
            "_source": {
                "options": [
                    {
                        "COMBINABLE": 1
                    }
                ]
            }
        }
    ]
}

The painless script above is pretty simple:

def options = ctx.options;
def pairs = new ArrayList();
for (def pair : options) {
  def k = false;
  if (pair["COMBINABLE"] == "1" || pair["COMBINABLE"] == 1) {
    k = true;
  }
  pair["COMBINABLE"] = k;
}
ctx.options = options;

It simply loop through all your option under options, then if the COMBINABLE is 1 or "1", it will convert to true, otherwise, it will be false. You can set the pipeline as your default ingestion, see here

  • Related