ElasticSearch 6.x 的 Rest API 基本没有变化,只是对 HTTP 请求的 contentType 进行了严格的规定,如果有请求体,那么必须在请求中说明请求体的格式。具体见官网的这篇文章:https://www.elastic.co/blog/strict-content-type-checking-for-elasticsearch-rest-requests
REST API
返回的 JSON 报文默认是未格式化的,比较难读。可以在请求 url 后加上 “?pretty”,使返回的 JSON 格式化显示(默认是显示一整行)。
新建文档
curl -H'Content-Type: application/json' -XPUT http://localhost:9200/books/article/1?pretty -d '{"title":"ElasticSearch", "content":"hello ElasticSearch"}'
这个命令可以建立 books 索引下 article 类型的标识符为 1 的一个文档。-d 参数后跟请求负载的文本。有报文体,所以要加 -H 参数。
运行结果如下:
{
"_index" : "books",
"_type" : "article",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
另外,如果不指定标识符,即使用 POST 请求类型不带标识符,可以自动生成一个唯一标识符。
curl -H'Content-Type: application/json' -XPOST http://localhost:9200/document/article/?pretty -d '{"title":"ElasticSearch", "content":"hello ElasticSearch"}'
运行结果如下:
{
"_index" : "document",
"_type" : "article",
"_id" : "RietQGEBGzSNMikIm2F2",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
检索文档
curl -XGET http://localhost:9200/books/article/1?pretty
将会返回:
{
"_index" : "books",
"_type" : "article",
"_id" : "1",
"_version" : 1,
"found" : true,
"_source" : {
"title" : "ElasticSearch",
"content" : "hello ElasticSearch"
}
}
更新文档
更新索引时,在内部,ES 必须首先获取该文档,从 _source 属性获得数据,删除旧的文件,更改 _source 属性,然后把它作为新的文档来索引。
curl -H'Content-Type: application/json' -XPOST http://localhost:9200/books/article/1/_update?pretty -d '{"script":{"source":"ctx._source.content = \"hello ES\""}}'
返回结果:
{
"_index" : "books",
"_type" : "article",
"_id" : "1",
"_version" : 2,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}
返回结果可以看到,result 为 updated,而且 version 变为了 2 ,说明更新成功了。为了确定更新成功,可以再查询一次,看结果字段的值是否更改了。
返回结果:
{
"_index" : "books",
"_type" : "article",
"_id" : "1",
"_version" : 2,
"found" : true,
"_source" : {
"title" : "ElasticSearch",
"content" : "hello ES"
}
}
可以看到版本号 version 为 2 ,而且 content 字段由 “hello ElasticSearch” 改为了 “hello ES”。
更新时,只需要发送改变的字段即可。
删除文档
删除某个文档加上对应的标识符即可
curl -XDELETE http://localhost:9200/books/article/1?pretty
删除时,version 也会加 1,运行结果为:
{
"_index" : "books",
"_type" : "article",
"_id" : "1",
"_version" : 3,
"result" : "deleted",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1
}