数据的增删改
新增數據
隨機生成id
通過POST請求,可以向一個已經存在的索引庫中添加數據。
語法:
POST /索引庫名/類型名 {"key":"value" }?示例:
POST /learn/goods/ {"title":"小米手機","images":"http://image.learn.com/12479122.jpg","price":2699.00 }響應:
{"_index": "learn","_type": "goods","_id": "r9c1KGMBIhaxtY5rlRKv","_version": 1,"result": "created","_shards": {"total": 3,"successful": 1,"failed": 0},"_seq_no": 0,"_primary_term": 2 }通過kibana查看數據:
get _search {"query":{"match_all":{}} } {"_index": "learn","_type": "goods","_id": "r9c1KGMBIhaxtY5rlRKv","_version": 1,"_score": 1,"_source": {"title": "小米手機","images": "http://image.learn.com/12479122.jpg","price": 2699} }-
_source:源文檔信息,所有的數據都在里面。
-
_id:這條文檔的唯一標示,與文檔自己的id字段沒有關聯
自定義id
如果我們想要自己新增的時候指定id,可以這么做:
POST /索引庫名/類型/id值 {... }示例:
POST /learn/goods/2 {"title":"大米手機","images":"http://image.learn.com/12479122.jpg","price":2899.00 }得到的數據:
{"_index": "learn","_type": "goods","_id": "2","_score": 1,"_source": {"title": "大米手機","images": "http://image.learn.com/12479122.jpg","price": 2899} }智能判斷
在學習Solr時我們發現,我們在新增數據時,只能使用提前配置好映射屬性的字段,否則就會報錯。
不過在Elasticsearch中并沒有這樣的規定。
事實上Elasticsearch非常智能,你不需要給索引庫設置任何mapping映射,它也可以根據你輸入的數據來判斷類型,動態添加數據映射。
測試一下:
POST /learn/goods/3 {"title":"超米手機","images":"http://image.learn.com/12479122.jpg","price":2899.00,"stock": 200,"saleable":true }我們額外添加了stock庫存,和saleable是否上架兩個字段。
來看結果:
{"_index": "learn","_type": "goods","_id": "3","_version": 1,"_score": 1,"_source": {"title": "超米手機","images": "http://image.learn.com/12479122.jpg","price": 2899,"stock": 200,"saleable": true} }在看下索引庫的映射關系:
{"learn": {"mappings": {"goods": {"properties": {"images": {"type": "keyword","index": false},"price": {"type": "float"},"saleable": {"type": "boolean"},"stock": {"type": "long"},"title": {"type": "text","analyzer": "ik_max_word"}}}}} }stock和saleable都被成功映射了。
修改數據
把剛才新增的請求方式改為PUT,就是修改了。不過修改必須指定id,
-
id對應文檔存在,則修改
-
id對應文檔不存在,則新增
比如,我們把id為3的數據進行修改:
PUT /learn/goods/3 {"title":"超大米手機","images":"http://image.learn.com/12479122.jpg","price":3899.00,"stock": 100,"saleable":true }結果:
{"took": 17,"timed_out": false,"_shards": {"total": 9,"successful": 9,"skipped": 0,"failed": 0},"hits": {"total": 1,"max_score": 1,"hits": [{"_index": "learn","_type": "goods","_id": "3","_score": 1,"_source": {"title": "超大米手機","images": "http://image.learn.com/12479122.jpg","price": 3899,"stock": 100,"saleable": true}}]} }刪除數據
刪除使用DELETE請求,同樣,需要根據id進行刪除:
語法
DELETE /索引庫名/類型名/id值?
總結