7. 批量获取文档:
使用es提供的Multi Get API,可以通过索引名、类型名、文档id一次得到一个文档集合.文档可以来自同一个索引库,也可以来自不同索引库.
(1). 批量获取指定文档所有字段:
curl 'http://localhost:9200/_mget' -H 'Content-Type: application/json' -d '{
"docs":[
{
"_index": "lib",
"_type": "user",
"_id": 1
},
{
"_index": "lib",
"_type": "user",
"_id": 2
}
]
}'
结果:
{
"docs" : [
{
"_index" : "lib",
"_type" : "user",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "Jane",
"age" : 32,
"interests" : [
"music"
]
}
},
{
"_index" : "lib",
"_type" : "user",
"_id" : "2",
"_version" : 1,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "Jane",
"age" : 32,
"interests" : [
"music"
]
}
}
]
}
(2). 批量获取指定文档指定具体的字段:
curl 'http://localhost:9200/_mget?pretty' -H 'Content-Type: application/json' -d '{
"docs":[
{
"_index": "lib",
"_type": "user",
"_id": 1,
"_source": "interests"
},
{
"_index": "lib",
"_type": "user",
"_id": 2,
"_source": ["age", "name"]
}
]
}'
结果:
{
"docs" : [
{
"_index" : "lib",
"_type" : "user",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"interests" : [
"music"
]
}
},
{
"_index" : "lib",
"_type" : "user",
"_id" : "2",
"_version" : 1,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "Jane",
"age" : 32
}
}
]
}
(3). 优化获取同索引同类型下的不同文档:
curl 'http://localhost:9200/lib/user/_mget?pretty' -H 'Content-Type: application/json' -d '{
"docs":[
{
"_id": 1,
"_source": "interests"
},
{
"_id": 2,
"_source": ["age", "name"]
}
]
}'
注:
①. 在url中指定索引与文档名称.
(4). 优化获取同索引同类型下的相同文档:
curl 'http://localhost:9200/lib/user/_mget?pretty' -H 'Content-Type: application/json' -d '{
"ids": ["1","2"]
}'