轉:
- 版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
- 本文鏈接:https://blog.csdn.net/liuxiao723846/article/details/78444472
mapping的寫入與查看
使用elasticsearch保存數據之前創建索引非常關鍵,一個好的索引使后續業務的查詢更加方便快捷,我們創建索引時如果不指定相關信息,會按照默認設置創建,如果我們想要更加強大的功能,比如中文檢索、拼音檢索、首拼檢索,就需要我們自己規划索引的創建,一般索引創建后不能更改,所以創建索引時要特別注意。下面是創建索引的最基礎的步驟,供新手們參考。
以下POST命令如果執行不成功可以換成PUT嘗試,本人在kibana軟件中親測有效。
1、首先創建一個索引:
curl -XPOST "http://127.0.0.1:9200/productindex"
命令執行正常則返回:{"acknowledged":true}
現在只創建了一個索引,並沒有設置mapping,查看一下索引mapping的內容:
curl -XGET "http://127.0.0.1:9200/productindex/_mapping?pretty"
{
"productindex" : {
"mappings" : { }
}
}
2、給索引添加屬性
可以看到mapping為空,我們只創建了一個索引,並沒有進行mapping配置,mapping自然為空。
下面給productindex這個索引加一個type,type name為product,並設置mapping:
curl -XPOST "http://127.0.0.1:9200/productindex/product/_mapping?pretty" -d '
{
"product": {
"properties": {
"title": {
"type": "string",
"store": "yes"
},
"description": {
"type": "string",
"analyzer": "standard"
},
"price": {
"type": "double"
},
"onSale": {
"type": "boolean"
},
"type": {
"type": "integer"
},
"createDate": {
"type": "date"
}
}
}
}
命令執行正常則返回:{"acknowledged" : true}
3、查看mapping結果
上面的操作中,我們給productindex加了一個type,並寫入了product的mapping信息,再次查看:
curl -XGET "http://127.0.0.1:9200/productindex/_mapping"
{
"productindex" : {
"mappings" : {
"product" : {
"properties" : {
"createDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"description" : {
"type" : "string",
"analyzer": "standard"
},
"onSale" : {
"type" : "boolean"
},
"price" : {
"type" : "double"
},
"title" : {
"type" : "string",
"store" : true
},
"type" : {
"type" : "integer"
}
}
}
}
}
}
4、修改mapping(新增一個新字段)
如果想給product新增一個字段,那么需要修改mapping,嘗試一下:
curl -XPOST "http://127.0.0.1:9200/productindex/product/_mapping
{
"product": {
"properties": {
"amount":{
"type":"integer"
}
}
}
}'
{
5、修改mapping(修改原有字段)
如果要修改一個字段的類型呢,比如onSale字段的類型為boolean,現在想要修改為string類型,嘗試一下:
curl -XPOST "http://127.0.0.1:9200/productindex/product/_mapping
{
"product": {
"properties": {
"onSale":{
"type":"string"
}
}
}
}
返回錯誤:
{
"error" : {
"root_cause" : [ {
"type" : "illegal_argument_exception",
"reason" : "mapper [onSale] of different type, current_type [boolean], merged_type [string]"
} ],
"type" : "illegal_argument_exception",
"reason" : "mapper [onSale] of different type, current_type [boolean], merged_type [string]"
},
"status" : 400
}
為什么不能修改一個字段的type?原因是一個字段的類型修改以后,那么該字段的所有數據都需要重新索引。Elasticsearch底層使用的是lucene庫,字段類型修改以后索引和搜索要涉及分詞方式等操作,不允許修改類型在我看來是符合lucene機制的。