ES設置mapping的方法
Mapping就是對索引庫中索引的字段名及其數據類型進行定義,類似於關系數據庫中表建立時要定義字段名及其數據類型,ES有默認的mapping,如果要自定義其分詞器、是否分詞、是否存儲等可以對其進行mapping設置。
1:配置文件設置方法
在ES安裝文件的config/mappings的目錄下新建index_name.json(index_name是要建立的索引名稱)
配置文件示例如下
{
"mappings":{
"properties":{
"name":{
"type":"string",
"store":"yes"
},
"ename":{
"type":"string",
"index":"not_analyzed"
},
"age":{
"type":"integer"
},
"marital":{
"type":"boolean"
},
"address":{
"properties" : {
"country" : {"type" : "string"},
"city" : {"type" : "string"}
}
},
"hobby":{
"type":"string",
"index_name" : "tag"
},
"createDate":{
"type":"date"
}
}
}
}
該配置文件在建立索引的時候會生成mapping映射關系,可以訪問curl -XGET 'http://localhost:9200/_mapping?pretty'查看或者在head中使用GET方式訪問http://localhost:9200/_mapping進行驗證
2:使用java api調用設置方法
public static void putMapping(Client client) throws IOException{
client.admin().indices().prepareCreate("test").execute().actionGet();
XContentBuilder mapping = jsonBuilder()
.startObject()
.startObject("test")
.startObject("properties")
.startObject("name").field("type", "string").field("store", "yes").endObject()
.startObject("ename").field("type", "string").field("index", "not_analyzed").endObject()
.startObject("age").field("type", "integer").endObject()
.startObject("marital").field("type", "boolean").endObject()
.startObject("address")
.startObject("properties")
.startObject("country").field("type","string").endObject()
.startObject("city").field("type","string").endObject()
.endObject()
.endObject()
.startObject("hobby").field("type", "string").field("index_name","tag").endObject()
.startObject("createDate").field("type", "date").endObject()
.endObject()
.endObject()
.endObject();
PutMappingRequest mappingRequest = Requests.putMappingRequest("test").type("t_test").source(mapping);
client.admin().indices().putMapping(mappingRequest).actionGet();
}
在訪問curl -XGET 'http://localhost:9200/_mapping?pretty'查看或者在head中使用GET方式訪問http://localhost:9200/_mapping進行驗證的時候如果沒有進行數據的初始化,properties節點下是空數據,直到有數據初始化后才顯示出各個字段的屬性