Home  >  Article  >  Database  >  Elasticsearch中的CRUD

Elasticsearch中的CRUD

PHPz
PHPzOriginal
2016-06-07 15:56:421830browse

在《玩玩儿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,我们可以再找些其他好玩儿的来玩儿了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn