Search code examples
elasticsearch

How can I add a field to existing mapping with values in other fields?


Current Mapping field is

      ...
      "latitude": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      ...

I wish to add a field 'location' using those data in latitude & longitude field. How can I implement?

    "location": {
      "type": "geo_point"
    }
  }

Solution

  • Currently, it is not possible to add and populate data for new fields in the existing index.

    The only way you can achieve it by reindexing data into new index.

    Let's say you have an index(source-index) test-geo-index with two fields(not restricted to two fields for easy understanding purpose I took only 2 fields) latitude and longitude as shown below:

    PUT test-geo-index
    {
      "mappings": {
        "test-geo-type": {
          "properties": {
            "longitute": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            },
            "latitude": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            }
          }
        }
      }
    }
    

    Now you can create a new index(dest-index) test-geo-updated-index with the above mapping and location field and populate data into it by using elasticsearch _reindex API.

    PUT test-geo-updated-index
    {
      "mappings": {
        "test-geo-type": {
          "properties": {
            "longitute": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            },
            "latitude": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            },
            "location": {
              "type": "geo_point"
            }
          }
        }
      }
    }
    

    Elasticsearch ReIndex API:

    POST _reindex
    {
      "source": {
        "index": "test-geo-index"
      },
      "dest": {
        "index": "test-geo-updated-index"
      },
      "script": {
        "inline": "ctx._source.location=ctx._source.latitude + \",\" + ctx._source.longitude"
      }
    }
    

    You can read more about Reindex API here