ES-使用映射來定義各種文檔
每篇文檔屬於一種類型,而每種類型屬於一個索引。從數據的邏輯划分來看,可以認為索引是數據庫,而類型是數據庫中的表。
類型包含了映射中每個字段的定義。映射包括了該類型的文檔中可能出現的所有字段,並告訴ES如何索引一篇文檔的多個字段。
類型只提供邏輯上的分離:
在ES中,不同類型的文檔沒有物理上的分離。在同一個ES索引中的所有文檔,無論何種類型,都是存儲在屬於相同分片的同一組文件中。一份分片就是一個Lucene的索引,類型的名稱是Lucene索引中一個字段。所有映射的所有字段都是Lucene索引中的字段。
類型的概念是針對ES的一層抽象,但不屬於Lucene。可以輕松地在同一個索引中擁有不同類型的文檔。ES負責分離這些文檔,在某個類型中搜索時,ES會過濾出屬於哪個類型的文檔。
當多個類型中出現同樣的字段名稱時,兩個同名的字段應該有同樣的設置。否則,ES將很難分辨查詢時指的是兩個字段中的哪一個。兩個字段都是屬於同一個Lucene索引。
group(分組)和event(活動)存儲在不同的類型中。ES允許在一個類型、多個類型中搜索。
1. 檢索和定義映射
1.1獲取目前的映射
為了查看某個字段類型當前的映射,向該類型URL的_mapping接口發送一個HTTP GET請求
FengZhendeMacBook - Pro: bin FengZhen$ curl 'localhost:9200/music/singer/_mapping?pretty' { "music": { "mappings": { "singer": { "properties": { "level": { "type": "string" }, "name": { "type": "string" } } } } } }
新建一個專輯類型album,並索引一篇新文檔
FengZhendeMacBook - Pro: bin FengZhen$ curl - XPUT 'localhost:9200/music/album/1' - d '{ "name": "八度空間", "date": "2003-10-25T19:00" }'
獲取當前類型映射
FengZhendeMacBook - Pro: bin FengZhen$ curl 'localhost:9200/music/album/_mapping?pretty' { "music": { "mappings": { "album": { "properties": { "date": { "type": "date", "format": "strict_date_optional_time||epoch_millis" }, "name": { "type": "string" } } } } } }
可看到date字段自動識別為日期類型
1.2定義新的映射
在索引music的album類型中,新增一個字段映射singer,類型為string
FengZhendeMacBook - Pro: bin FengZhen$ CURL - XPUT 'localhost:9200/music/_mapping/album' - d '{ "album": { "properties": { "singer": { "type": "string" } } } }'
查看album的映射
FengZhendeMacBook - Pro: bin FengZhen$ curl 'localhost:9200/music/album/_mapping?pretty' { "music": { "mappings": { "album": { "properties": { "date": { "type": "date", "format": "strict_date_optional_time||epoch_millis" }, "name": { "type": "string" }, "singer": { "type": "string" } } } } } }
2.擴展現有的映射
如果在現有的基礎上再設置一個映射,ES會將兩者合並。如上述映射,包含兩個來自初始映射的字段,外加定義的一個新字段。隨着新字段的加入,初始的映射被擴展了,在任何時候都可以進行這樣的操作,ES將次稱為現有映射和先前提供的映射的合並。
但是,並非所有的合並都是奏效的,例如:無法改變現有字段的數據類型,而且通常無法改變一個字段被索引的方式。
試圖改變singer類型為long,操作會失敗並拋出異常
FengZhendeMacBook - Pro: bin FengZhen$ CURL - XPUT 'localhost:9200/music/_mapping/album?pretty' - d '{ "album": { "properties": { "singer": { "type": "long" } } } }' { "error": { "root_cause": [{ "type": "illegal_argument_exception", "reason": "mapper [singer] of different type, current_type [string], merged_type [long]" }], "type": "illegal_argument_exception", "reason": "mapper [singer] of different type, current_type [string], merged_type [long]" }, "status": 400 }
避免這個錯誤唯一的方法是重新索引album里的所有數據,步驟如下
(1) 將album類型里的所有數據刪除。
(2) 設置新的映射
(3) 再次索引所有的數據