mapping的寫入與查看
首先創建一個索引:
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" : { } } }
可以看到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", "index": "not_analyzed" }, "price": { "type": "double" }, "onSale": { "type": "boolean" }, "type": { "type": "integer" }, "createDate": { "type": "date" } } } } ' { "acknowledged" : true }
上面的操作中,我們給productindex加了一個type,並寫入了product的mapping信息,再次查看:
curl -XGET "http://127.0.0.1:9200/productindex/_mapping?pretty" { "productindex" : { "mappings" : { "product" : { "properties" : { "createDate" : { "type" : "date", "format" : "strict_date_optional_time||epoch_millis" }, "description" : { "type" : "string", "index" : "not_analyzed" }, "onSale" : { "type" : "boolean" }, "price" : { "type" : "double" }, "title" : { "type" : "string", "store" : true }, "type" : { "type" : "integer" } } } } } }
修改mapping
如果想給product新增一個字段,那么需要修改mapping,嘗試一下:
curl -XPOST "http://127.0.0.1:9200/productindex/product/_mapping?pretty" -d '{ "product": { "properties": { "amount":{ "type":"integer" } } } }' { "acknowledged" : true }
新增成功。
如果要修改一個字段的類型呢,比如onSale字段的類型為boolean,現在想要修改為string類型,嘗試一下:
curl -XPOST "http://127.0.0.1:9200/productindex/product/_mapping?pretty" -d '{ "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機制的。
這里有一篇關於修改mapping字段的博客,敘述的比較清楚:Elasticsearch 的坑爹事——記錄一次mapping field修改過程,可以參考.