elasticsearchaws-elasticsearchelasticsearch-mappingelasticsearch-schema

How to create a custom reusable type in ElasticSearch?


My json for ElasticSearch schema looks like this :-

{
  "mappings": {
    "properties": {
      "DESCRIPTION_FR": {
        "type": "text",
        "analyzer": "french"
      },
      "FEEDBACK_FR": {
        "type": "text",
        "analyzer": "french"
      },
      "SOURCE_FR": {
        "type": "text",
        "analyzer": "french"
      }
    }
  }
}

There are 100 of properties like this. Replicating a change across all the properties with this approach is redundant and erroneous.

Is there a way in ElasticSearch 7.2 to write custom data type and reuse it in property mapping.

{
  "settings": {
  //definition of custom type "text_fr"
 },
  "mappings": {
    "properties": {
      "DESCRIPTION_FR": {
        "type": "text_fr"
      },
      "FEEDBACK_FR": {
        "type": "text_fr"
      },
      "SOURCE_FR": {
        "type": "text_fr"
      }
    }
  }
}

Solution

  • Yes! What you're after is dynamic mapping templates. More specifically the match feature.

    1. Define the target field names with a leading wildcard:
    PUT my_index
    {
      "mappings": {
        "dynamic_templates": [
          {
            "is_french_text": {
              "match_mapping_type": "*",
              "match": "*_FR",
              "mapping": {
                "type": "text",
                "analyzer": "french"
              }
            }
          }
        ]
      }
    }
    
    1. Insert a doc:
    POST my_index/_doc
    {
      "DESCRIPTION_FR": "je",
      "FEEDBACK_FR": "oui",
      "SOURCE_FR": "je ne sais quoi"
    }
    
    1. Verify the dynamically generated mapping:
    GET my_index/_mapping