Map all keys under a key to string


(Justin Yeh) #1

Hi, I'm trying to make elasticsearch map all keys under a specific key to a string value. I know the parent key name, but the nested keys can be of arbitrary key name and value type.

For example, two json blobs:

{
"key1":"stringvalue",
"key2": {
"arbitraryname1": 0
}
}

{
"key1":"stringvalue",
"key2": {
"arbitraryname1": "stringvalue"
}
}

I'm not sure how to map the above so that "arbitraryname1":0 and "arbitraryname1":"stringvalue" both get mapped as strings: "arbitraryname1":"1" and "arbitraryname1":"stringvalue"

I need to do this because the value type of arbitraryname1 can change. I also can't do an explicit mapping on arbitraryname1 because i do not know the key names ahead of time.

So what I want is just to say "for all entries underneath key2, map those as strings". Is there some way to do this?

Thanks!


(Clinton Gormley) #2

Use path_match for this:

PUT t
{
  "mappings": {
    "t": {
      "dynamic_templates": [
        {
          "arbitrary_as_strings": {
            "path_match": "key2.*",
            "mapping": {
              "type": "keyword"
            }
          }
        }
      ]
    }
  }
}

PUT t/t/1
{
  "key1": "stringvalue",
  "key2": {
    "arbitraryname1": 0
  }
}

GET _mapping

returns:

{
  "t": {
    "mappings": {
      "t": {
        "dynamic_templates": [
          {
            "arbitrary_as_strings": {
              "path_match": "key2.*",
              "mapping": {
                "type": "keyword"
              }
            }
          }
        ],
        "properties": {
          "key1": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "key2": {
            "properties": {
              "arbitraryname1": {
                "type": "keyword"
              }
            }
          }
        }
      }
    }
  }
}

(system) #3

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