Mapping,就是對索引庫中索引的欄位名及其資料類型進行定義,類似於關聯式資料庫中表建立時要定義欄位名及其資料類型那樣,不過es的mapping比資料庫靈活很多,它可以動態添加欄位。一般不需要要指定mapping都可以,因為es會自動根據資料格式定義它的類型,如果你需要對某些欄位添加特殊屬性(如:定義使用其它分詞器、是否分詞、是否儲存等),就必須手動添加mapping。有兩種添加mapping的方法,一種是定義在設定檔中,一種是運行時手動提交mapping,兩種選一種就行了。
先介紹在設定檔中定義mapping,你可以把[mapping名].json檔案放到config/mappings/[索引名]目錄下,這個目錄要自己建立,一個mapping和一個索引對應,你也可以定義一個預設的mapping,把自己定義的default-mapping.json放到config目錄下就行。json格式如下:
{ "mappings":{ "properties":{ "title":{ "type":"string", "store":"yes" }, "description":{ "type":"string", "index":"not_analyzed" }, "price":{ "type":"double" }, "onSale":{ "type":"boolean" }, "type":{ "type":"integer" }, "createDate":{ "type":"date" } } }}
接下來介紹通過請求添加mapping,下面為一個添加productIndex索引庫的mapping的json格式請求。其中productIndex為索引類型,properties下面的為索引裡面的欄位,type為資料類型,store為是否儲存,"index":"not_analyzed"為不對該欄位進行分詞。
{ "productIndex":{ "properties":{ "title":{ "type":"string", "store":"yes" }, "description":{ "type":"string", "index":"not_analyzed" }, "price":{ "type":"double" }, "onSale":{ "type":"boolean" }, "type":{ "type":"integer" }, "createDate":{ "type":"date" } } }}
用java api調用的代碼如下:
先建立空索引庫
client.admin().indices().prepareCreate("productIndex").execute().actionGet();
put mapping
XContentBuilder mapping = jsonBuilder() .startObject() .startObject("productIndex") .startObject("properties") .startObject("title").field("type", "string").field("store", "yes").endObject() .startObject("description").field("type", "string").field("index", "not_analyzed").endObject() .startObject("price").field("type", "double").endObject() .startObject("onSale").field("type", "boolean").endObject() .startObject("type").field("type", "integer").endObject() .startObject("createDate").field("type", "date").endObject() .endObject() .endObject() .endObject(); PutMappingRequest mappingRequest = Requests.putMappingRequest("productIndex").type("productIndex").source(mapping); client.admin().indices().putMapping(mappingRequest).actionGet();