ElasticSearch-query-multi-get批处理
2025-01-22 08:19:30    829 字   
This post is also available in English and alternative languages.

ElasticSearch版本:6.5.0(点击跳转官方文档)

ElasticSearch multi-get/mget 检索多个文档/批处理

在Elasticsearch中,检索多个文档虽然很快,但合并多个请求可以减轻网络开销。可以使用 multi-get 或者 mget。

下面示例模拟,从三个索引中查找文档。

如果想指定返回字段,增加一个_source参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
GET /_mget
{
"docs":[
{
"_index":"demo",
"_type":"testDate",
"_id":"1"
},{
"_index": "megacorp",
"_type": "employee",
"_id": "5"
},{
"_index": "books",
"_type": "book",
"_id": "19",
"_source":"publish"
}
]
}

响应报文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
{
"docs": [
{
"_index": "demo",
"_type": "testDate",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"name": "cyx111",
"age": "11",
"address": "nanjing11"
}
},
{
"_index": "megacorp",
"_type": "employee",
"_id": "5",
"_version": 1,
"found": true,
"_source": {
"about": "i love evertything",
"last_name": "yixin",
"interests": [
"read book",
"swim"
],
"first_name": "cheng",
"age": "22"
}
},
{
"_index": "books",
"_type": "book",
"_id": "19",
"_version": 2,
"found": true,
"_source": {
"publish": "高等教育出版社"
}
}
]
}

如果想检索的多个文档,都在一个_index中(甚至在一个_type中),url中就可以指定_index、_type

1
2
3
4
5
6
7
8
9
10
GET /demo/testDate/_mget
{
"docs":[
{
"_id":"2"
},{
"_id":"3"
}
]
}

响应报文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
"docs": [
{
"_index": "demo",
"_type": "testDate",
"_id": "2",
"_version": 2,
"found": true,
"_source": {
"name": "cyx2",
"age": "23",
"address": "nanjing2",
"price": "100.00",
"tags": [
"test",
"test2",
"test3"
]
}
},
{
"_index": "demo",
"_type": "testDate",
"_id": "3",
"_version": 1,
"found": true,
"_source": {
"name": "cyx333",
"age": "333",
"address": "nanjing333"
}
}
]
}

如果,多个文档都是同一个索引、类型下,可以换这种写法:

1
2
3
4
GET /demo/testDate/_mget
{
"ids":["1","2"]
}

响应报文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
"docs": [
{
"_index": "demo",
"_type": "testDate",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"name": "cyx111",
"age": "11",
"address": "nanjing11"
}
},
{
"_index": "demo",
"_type": "testDate",
"_id": "2",
"_version": 2,
"found": true,
"_source": {
"name": "cyx2",
"age": "23",
"address": "nanjing2",
"price": "100.00",
"tags": [
"test",
"test2",
"test3"
]
}
}
]
}

如果,其中某个文档不存在,返回的结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"docs": [
{
"_index": "demo",
"_type": "testDate",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"name": "cyx111",
"age": "11",
"address": "nanjing11"
}
},
{
"_index": "demo",
"_type": "testDate",
"_id": "pppp",
"found": false
}
]
}

不存在的文档,并不影响第一个文档的检索,每个文档的检索都是独立的。