映射(Mapping)
概念:創建索引時,可以預先定義字段的類型以及相關屬性。從而使得索引建立得更加細致和完善。如果不預先設置映射,會自動識別輸入的字段類型。
官方文檔(字段數據類型):https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html
官方文檔(映射參數):https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-params.html
映射分為靜態映射和動態映射:
動態映射:文檔中碰到一個以前沒見過的字段時,動態映射可以自動決定改字段的類型,並對改字段添加映射。通過dynamic屬性進行控制,默認值為true,動態添加;false忽略新字段;strict碰到陌生字段拋出異常。
建立靜態映射:
curl -XPOST 'http://localhost:9200/library' -d ' { "settings": { "number_of_shards": 5, "number_of_replicas": 1 }, "mappings": { "books": { "properties": { "title": { "type": "string" }, "name": { "type": "string", "index": "not_analyzed" }, "publish_date": { "type": "date", "index": "not_analyzed" }, "price": { "type": "double" }, "number": { "type": "integer" } } } } } '
動態映射:
必須為object類型才能添加dynamic動態映射
{ "mappings": { "books": { "dynamic": "strict", "properties": { "title": { "type": "string" }, "name": { "type": "string", "index": "not_analyzed" }, "publish_date": { "type": "date", "index": "not_analyzed" }, "price": { "type": "double" }, "number": { "type": "object", "dynamic": true } } } } }
獲取某個索引下的映射信息
curl -XGET localhost:9200/library/_mapping
更新修改映射
mapping一旦建立,就不能修改現有的字段映射。如果要推倒現有的映射,必須得重新建立一個索引,然后重新定義映射,將之前索引里的數據導入到新建立得索引中。
- 給現有的索引定義一個別名,並且把現有的索引指向這個別名
- 運行 curl -XPUT localhost:9200/現有索引/_alias/別名A
- 新創建一個索引,定義好最新的映射
- 將別名指向新的索引,並且刪除之前索引的執行
- 運行
curl -XPOST 'localhost:9200/_aliases' -d ' { "actions": [ { "remove": { "index": "現有索引名", "alias": "別名A" } }, { "add": { "index": "新建索引名", "alias": "別名A" } } ] } '
以上無需停機即可完成。