參考官方文檔:
問題
我們有一個標籤,所以這個標籤會有很多,而且都是用戶自己的標籤,會有各種各樣的內容。如果使用動態映射列,第一次可能就是數字類型,而後進來其它的字符就全是無法轉換的錯誤。
解決
elasticsearch提供了一個默認的配置可以設置動態映射列的格式。
簡單來說,就是匹配新加入的列的名稱,如果匹配成功,則使用設置好的類型。
json格式
PUT /my_index
{
"mappings": {
"my_type": {
"dynamic_templates": [
{ "es": {
"match": "*_es",
"match_mapping_type": "string",
"mapping": {
"type": "string",
"analyzer": "spanish"
}
}},
{ "en": {
"match": "*",
"match_mapping_type": "string",
"mapping": {
"type": "string",
"analyzer": "english"
}
}}
]
}}}
PUT _template/logging
{
"template": "logs-*",
"settings": { "number_of_shards": 1 },
"mappings": {
"_default_": {
"_all": {
"enabled": false
},
"dynamic_templates": [
{
"strings": {
"match_mapping_type": "string",
"mapping": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed",
"ignore_above": 256
}
}
}
}
}
]
}
}
}
PUT logs-2015.10.01/event/1
{ "message": "error:16" }
以上兩段內容來自官方文檔。
這裏的字段名稱已經非常明白了,我就不講解了。
java格式
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject(typeName)
.startArray("dynamic_templates")
.startObject()
.startObject("all_tag_string")
.field("match", "tag_*")
// .field("match_mapping_type","string")
.field("match_mapping_type", "*")
.startObject("mapping")
.field("type", "string")
.endObject()
.endObject()
.endObject()
.endArray()
.field("dynamic_date_formats", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd")
.startObject("properties")
.startObject("customer_list")
.field("type", "nested")
.endObject()
.startObject("goods_list")
.field("type", "nested")
.endObject()
.endObject()
.endObject().endObject();
這段代碼的意思是,設置默認的時間格式爲我們常用的格式,設置了兩種。另外所有列名以 tag_ 開頭的都設置爲string類型
//es提供的一些查詢方法
IndicesExistsResponse//判斷index是否存在
TypesExistsResponse//判斷type是否存在
DeleteMappingRequest//刪除mapping,可刪除index,type
PutMappingRequest//創建mapping,可以使用XContentBuilder參數