Multi Get Api
该 API 可以基于索引、类型(可选)以及 id (和可能的路由)获取多个文档。响应会包含一个 docs 数组,里面有获取到的所有的文档,并以原始请求的顺序排列(如果某一个请求失败了,该响应结果会有一个包含错误的对象)。得到的成功结构与通过 Get Api 获取的结构是一样的。
示例:
GET /_mget{"docs" : [{"_index" : "test","_type" : "_doc","_id" : "1"},{"_index" : "test","_type" : "_doc","_id" : "2"}]}curl -X GET "localhost:9200/_mget?pretty" -H 'Content-Type: application/json' -d'{"docs" : [{"_index" : "test","_type" : "_doc","_id" : "1"},{"_index" : "test","_type" : "_doc","_id" : "2"}]}'
mget 用于索引
这种情况下 body 中就不需要了:
GET /test/_mget{"docs" : [{"_type" : "_doc","_id" : "1"},{"_type" : "_doc","_id" : "2"}]}
mget 用于 type
GET /test/_doc/_mget{"docs" : [{"_id" : "1"},{"_id" : "2"}]}
这种情况下,可以直接使用 ids 来简化请求:
GET /test/_doc/_mget{"ids" : ["1", "2"]}
返回 Source 字段过滤
默认情况下,_source 字段会为每一个文档返回(如果存储过)。类似于 Get 接口,通过使用 _source 参数可以返回 _source字段的部分(甚至是不返回)。也可以在没有每个文档指令的情况下使用 url 参数 _source,_source_include & _source_exclude 来指定默认返回。
如:
GET /_mget{"docs" : [{"_index" : "test","_type" : "_doc","_id" : "1","_source" : false},{"_index" : "test","_type" : "_doc","_id" : "2","_source" : ["field3", "field4"]},{"_index" : "test","_type" : "_doc","_id" : "3","_source" : {"include": ["user"],"exclude": ["user.location"]}}]}
字段
可以为每个要获取的文档指定要检索的特定存储字段,类似于 Get API 的 stored_fields 参数。如:
GET /_mget{"docs" : [{"_index" : "test","_type" : "_doc","_id" : "1","stored_fields" : ["field1", "field2"]},{"_index" : "test","_type" : "_doc","_id" : "2","stored_fields" : ["field3", "field4"]}]}
或者,可以在查询字符串中指定 stored_fields 作为应用于所有文档的默认值。
GET /test/_doc/_mget?stored_fields=field1,field2{"docs" : [{"_id" : "1" (1)},{"_id" : "2","stored_fields" : ["field3", "field4"] (2)}]}
- 返回
field1及field2- 返回
field3及field4
路由
可以指定路由值作为参数:
GET /_mget?routing=key1{"docs" : [{"_index" : "test","_type" : "_doc","_id" : "1","routing" : "key2"},{"_index" : "test","_type" : "_doc","_id" : "2"}]}
该例子中,文档 test/_doc/2 会从与路由键 key1 对应的分片中获取,而文档 test/_doc/1 将会从与路由键 key2 对应的分片中获取。
