1 批量查询
批量查询,就是一条一条的查询。比如说要查询100条数据,普通查询就要发送100次网络请求,这个开销是很大的。如果采用批量查询的话,查询100条数据,就只要发送1次网络请求,网络请求的性能开销缩减100倍。
2 API: mget
2.1 普通查询
ES 中查询数据最简单的方式就是通过 GET ,一次查询一条数据,如查询 id 为 1 和id 为 2 的数据。
GET /test_index/test_type/1
GET /test_index/test_type/2
2.2 批量查询
在 ES 中要实现批量查询可以通过 mget 来实现。
(1)查询 id 为 1 和id 为 2 的数据。
GET /_mget
{
"docs" : [
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : 1
},
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : 2
}
]
}
查询结果:
{
"docs": [
{
"_index": "test_index",
"_type": "test_type",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"test_field1": "test field1",
"test_field2": "test field2"
}
},
{
"_index": "test_index",
"_type": "test_type",
"_id": "2",
"_version": 1,
"found": true,
"_source": {
"test_content": "my test"
}
}
]
}
(2)查询同一个 index 下的不同 type 的数据。
GET /test_index/_mget
{
"docs" : [
{
"_type" : "test_type",
"_id" : 1
},
{
"_type" : "test_type",
"_id" : 2
}
]
}
(3)查询同一个index下的同一个type下的数据。
GET /test_index/test_type/_mget
{
"ids": [1, 2]
}
3 mget 的重要性
一般来说,在进行查询的时候,如果一次性要查询多条数据的话,那么一定要用 batch 批量操作的 API 。这样可以尽可能减少网络开销次数,可将性能提升数倍,甚至数十倍。
mget 正是 ES 提供的批量操作的 API ,所以重要性不言而喻。
参考资料:http://www.roncoo.com/article/detail/128304