跳到主要內容

ElasticSearch rename field name in index



前言

傳統的關連式資料庫 (Relational Database, RDB), 若想要變更資料表內的欄位名稱可以用一行指令簡單地做到

MS SQL
sp_rename 'table_name.old_column_name', 
'new_column_name', 'COLUMN';


PostgreSQL
ALTER TABLE Test1 RENAME COLUMN foo TO baz;

但如果想要在ElasticSearch上修改欄位的話就沒有這麼簡單了

假設現在有個 Index "user"
PUT /user HTTP/1.1
Content-Type: application/json
{
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_doc": {
      "properties": {
        "devOs": {
          "type": "keyword"
        },
        "devOsVer": {
          "type": "keyword"
        },
        "appVer": {
          "type": "keyword"
        }
     }
  }
}

如果想要將欄位 appVer 改成 ver, 基本上需要以下的步驟

Step 1. 用更新後的 Mapping 建立一個暫時的 Index, user_tmp

PUT /User_tmp HTTP/1.1
Content-Type: application/json
{
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_doc": {
      "properties": {
        "devOs": {
          "type": "keyword"
        },
        "devOsVer": {
          "type": "keyword"
        },
        "ver": {
          "type": "keyword"
        }
     }
  }
}

Step 2. 把 user 的資料 Reindex 到 user_tmp

作 Reindex 的時候, 定義 script 將資料從舊的欄位 appVer 搬移到新的欄位 ver, 然後再刪除舊的欄位 "appVer"
POST /_reindex HTTP/1.1
Content-Type: application/json
{
  "source": {
    "index": "user"
  },
  "dest": {
    "index": "user_tmp"
  },
  "script": {
    "source": "ctx._source.ver = ctx._source.appVer; ctx._source.remove(\"appVer\") "
  }
}


Step 3. 刪除 user

DELETE /user HTTP/1.1

Step 4. 重建 user 的 Mapping

PUT /user HTTP/1.1
Content-Type: application/json
{
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_doc": {
      "properties": {
        "devOs": {
          "type": "keyword"
        },
        "devOsVer": {
          "type": "keyword"
        },
        "ver": {
          "type": "keyword"
        }
     }
  }
}


Step 5. 還原 user 的資料

POST /_reindex HTTP/1.1
Content-Type: application/json
{
  "source": {
    "index": "user_tmp"
  },
  "dest": {
    "index": "user"
  }
}

Step 6. 刪除 user_tmp

DELETE /user_tmp HTTP/1.1


留言