2021年3月5日 星期五

[Elasticsearch] Adjust index mapping by using reindex

最近在做的 log 遇到一開始沒有設定 index mapping type,所以 elasticsearch 自動判斷 value 給予 long type,但實際上該欄位資料應該是 float,只是剛好 index doc 那一筆是整數,讓 ES 判斷為 long。

以下範例說明: 

PUT test-index
POST test-index/_doc
{
  "name":"xxx",
  "price":22
}

建完 index 新增第一筆資料,再查詢 mapping api,會看到 price 為 long type

GET test-index/_mapping/

{
  "test-index" : {
    "mappings" : {
      "properties" : {
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "price" : {
          "type" : "long"
        }
      }
    }
  }
}

接著新增其他資料,price type 也一直會是 long

POST test-index/_doc
{
  "name":"yyy",
  "price":10.5
}

下面就進入這篇的重點啦,利用 elasticsearch 提供的 reindex api 將錯誤的 type 歸正。

首先需要新增一個 backup index,然後將其 price properties mapping type 修改為 float 。

PUT test-index-bak
PUT test-index-bak/_mapping
{
  "properties": {
    "price":{
      "type":"float"
    }
  }
}

查看一下

GET test-index-bak/_mapping/field/price
{
  "test-index-bak" : {
    "mappings" : {
      "price" : {
        "full_name" : "price",
        "mapping" : {
          "price" : {
            "type" : "float"
          }
        }
      }
    }
  }
}

接著就是將原本的資料透過 reindex 匯入 backup index

POST _reindex
{
  "source": {
    "index": "test-index"
  },
  "dest": {
    "index": "test-index-bak"
  }
}

匯入完以後刪掉原有的 index,再重複一次上面的動作,只是這次是針對原有的 test-index 做操作,再將備份的資料倒回來。

DELETE test-index
PUT test-index

PUT test-index/_mapping
{
  "properties": {
    "price":{
      "type":"float"
    }
  }
}

GET test-index/_mapping/

POST _reindex
{
  "source": {
    "index": "test-index-bak"
  },
  "dest": {
    "index": "test-index"
  }
}
DELETE test-index-bak

最後刪掉 backup index 就結束啦,是不是很簡單~~