在《玩玩儿elasticsearch》中简单介绍了一下elasticsearch。这篇文章,我们还是做些基础的学习,在elasticsearch如何进行crud?
课程推荐→:《elasticsearch全文搜索实战》(实战视频)
来自课程《千万级数据并发解决方案(理论+实战)》
假设我们正在创建的一个类似微博的应用,我们就姑且先叫它“kiwi”吧。kiwi这个应用就是一条条消息组成的。
在kiwi中,消息称为ksay。有两个部分组成,一是作者(author),而是消息本身(message)。
create
curl -x post http://localhost:9200/kiwi/ksay/ -d '{ author: rococojie, message: i am beautiful}'
返回:{_index:kiwi,_type:ksay,_id:aax3p2ljsp-ddyvy0usv7q,_version:1,created:true}
我们注意到elasticsearch默认不是按照自增的方式帮我们生成id的。而是自动生成22位的url安全的_id。如刚才的例子中,返回的_id就是aax3p2ljsp-ddyvy0usv7q。如果要使用自定义的_id,则操作如下:
curl -x post http://localhost:9200/kiwi/ksay/1 -d '{author: jerry, message: i hate tom}'
返回:{_index:kiwi,_type:ksay,_id:1,_version:1,created:true}
read
我们这里就只说用id取值
curl -x get http://localhost:9200/kiwi/ksay/1
返回:{_index:kiwi,_type:ksay,_id:1,_version:1,found:true, _source : { author: jerry, message: i hate tom}}
如果我们希望返回的知识原来我们存的数据,那么
curl -x get http://localhost:9200/kiwi/ksay/1/_source
返回:{ author: jerry, message: i hate tom}
curl -x get http://localhost:9200/kiwi/ksay/10000
返回{_index:kiwi,_type:ksay,_id:10000,found:false},没有找到我们刚才存的ksay。
update
curl -x put http://localhost:9200/kiwi/ksay/1 -d '{author: jerry, message: i love tom}'
返回:{_index:kiwi,_type:ksay,_id:1,_version:2,created:false}
我们注意到这里的_version变为了2,知识因为ksay发生了改变。created返回false,表示没有创建新的文档,只是更新。
虽然elasticsearch支持进行文档更新,我们需要知道elasticsearch中存储的文档是不可变的(immutable)。这种所谓的更新实际上是一种假象,在elasticsearch内部,首先将比较旧的那条数据标明为“已经删除”,然后再把较新的那条数据进行index。(retrieve-change-reindex)
部分更新
curl -x post http://localhost:9200/kiwi/ksay/1/_update -d '{ doc: {message: i hate tom, again} }'
返回:{_index:kiwi,_type:ksay,_id:1,_version:3}
doc中即是我们需要更新的field。elasticsearch会把最新的field“merge”到原来旧的文档中。这是我们再去查看这条ksay的信息。
curl -x get http://localhost:9200/kiwi/ksay/1
返回:{_index:kiwi,_type:ksay,_id:1,_version:3,found:true, _source : {author:jerry,message:i hate tom, again}}
delete
curl -x delete http://localhost:9200/kiwi/ksay/1
返回:{found:true,_index:kiwi,_type:ksay,_id:1,_version:4}
再尝试去取ksay:
curl -x get http://localhost:9200/kiwi/ksay/1
返回:{_index:kiwi,_type:ksay,_id:1,found:false}
就不能在访问到,found的值是false
学会了elasticsearch最基本的crud,我们可以再找些其他好玩儿的来玩儿了