7、批量操作——bulk API 介绍
先看一个批量创建文档的例子
curl -XPOST 'http:
//localhost:9200/test/article/_bulk?pretty' -d '
{
"index" : {
"_id" :
"3" } }
{
"id" :
3,
"subject" :
"第三篇文章标题",
"content" :
"第三篇文章内容" ,
"author":
"jam"}
{
"index" : {
"_id" :
"4" } }
{
"id" :
4,
"subject" :
"第四篇文章标题",
"content" :
"第四篇文章内容" ,
"author":
"tomi"}
'
#返回
{
"took" :
36,
"errors" :
false,
"items" : [ {
"index" : {
"_index" :
"test",
"_type" :
"article",
"_id" :
"3",
"_version" :
1,
"_shards" : {
"total" :
2,
"successful" :
1,
"failed" :
0
},
"status" :
201
}
}, {
"index" : {
"_index" :
"test",
"_type" :
"article",
"_id" :
"4",
"_version" :
1,
"_shards" : {
"total" :
2,
"successful" :
1,
"failed" :
0
},
"status" :
201
}
} ]
}
bulk API允许我们使用单一请求来实现多个文档的 create(文档不存在���才创建) 、 index(创建新文档或替换已有文档) 、 update 或 delete
它的请求体格式如下(也就是 -d 后面的数据)
{ action:
{ metadata
}}\n
{ request body
}\n
{ action:
{ metadata
}}\n
{ request body
}\n
action 有四个选项,即 create 、 index 、 update 、 delete
metadata 为元数据,即是 _index 、_type、_id,上面的例子中,因为我在请求链接中指定了 _index (test)和_type(article),所以我只需指定 _id
request body 这里就是每条数据的具体内容,字段名和数据一一对应就可以了
需要注意的是每行必须以 “\n” 符号结尾, 包括最后一行。直接敲回车键就可以了
可以在一条 bulk 的请求体中既执行 index(创建文档),又执行 update(更新文档),还可以执行 delete(删除文档),请求体类似如下
{ "
delete":
{ "_index": "test", "_type": "article", "_id": "1" }}
{ "
create":
{ "_index": "test", "_type": "article", "_id": "123" }}
{ "
id" :
123,"
subject" :
"第123篇文章标题","
content" :
"第123篇文章内容" ,"
author":
"jam123"}
{ "
index":
{ "_index": "test", "_type": "article", "_id": "3" }}
{ "
id" :
3,"
subject" :
"第三篇文章标题-替换后","
content" :
"第三篇文章内容-替换后" ,"
author":
"jam0"}
{ "
update":
{ "_index": "test", "_type": "article", "_id": "4"} }
{ "
doc" :
{"content" : "第四篇文章内容-更新后"} }
delete 操作没有请求体,所以后面紧跟另一个操作
三、Elasticsearch 的 DSL(特定领域语言) 查询
以 json 请求体的形式查询数据
1、基本查询
查询所有文档
等同于 curl -XGET ‘:9200/test/article/_search?pretty’
curl -XGET
'https://localhost:9200/test/article/_search?pretty' -d '
{
"query": {
"match_all": {}
}
}'
#返回
{
# 用时 毫秒
"took" :
4,
"timed_out" :
false,
#分片信息
"_shards" : {
"total" :
5,
"successful" :
5,
"failed" :
0
},
"hits" : {
#文档数
"total" :
3,
"max_score" :
1.0,
"hits" : [ {
"_index" :
"test",
"_type" :
"article",
"_id" :
"AVf_6fM1vEkwGPLuUJqp",
"_score" :
1.0,
"_source" : {
"id" :
2,
"subject" :
"第二篇文章标题",
"content" :
"第二篇文章内容",
"author" :
"jam"
}
}, {
"_index" :
"test",
"_type" :
"article",
"_id" :
"4",
"_score" :
1.0,
"_source" : {
"id" :
4,
"subject" :
"第四篇文章标题",
"content" :
"第四篇文章内容-更新后",
"author" :
"tomi"
}
}, {
"_index" :
"test",
"_type" :
"article",
"_id" :
"3",
"_score" :
1.0,
"_source" : {
"id" :
3,
"subject" :
"第三篇文章标题",
"content" :
"第三篇文章内容",
"author" :
"jam"
}
} ]
}
}