Make several fields from one nested field

Hello! I've an index which has a field called properties (besides the one that is defined in the top-level) in mappings with this structure:

"properties": {
  "type": "nested",
  "properties": {
    "code": {
      "type": "keyword"
    },
    "value": {
      "type": "keyword"
    }
  }
}

The data that is loaded in it looks like this:
Screenshot 2022-03-09 at 2.02.18 PM
(I omitted some parts of the data due to the confidentiality reasons)

The question is, how could I make several fields containing each of the values "code" as a field name and "value" as the fields value based on the content of this nested field so that it would look like this?

Looking forward to your reply!

first,you must find out all code value and put them in mappings:

POST index/_search
{
  "size": 0,
  "aggs": {
    "agg1": {
      "nested": {
        "path": "properties"
      },
      "aggs": {
        "agg2": {
          "terms": {
            "field": "properties.code"
          }
        }
      }
    }
  }
}

then use this DSL update your index:

POST index/_update_by_query
{
  "query": {
    "match_all": {}
  },
  "script": {
    "source": """
        ArrayList list = ctx._source.properties;
        for(HashMap map:list){
            ctx._source.put(map.get('code'),map.get('value'));
        }
    """,
    "lang": "painless"
  }
}

It worked, thanks a lot!
Could you please tell me if there is an option to not include the fields in the record if they are not present in "properties" field in this exact record?

And the other problem that I haven't been able to solve is the mapping type for the new fields. Is there ant way to make them be "keyword" while performing the update by query?

Looking forward to your answer!

first q:use map.containsKey(xxx) to judge
sec q: use dynamic_template

Thank you a lot, you really helped me out!

My pleasure

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.