multiGet API并行地在单个http请求中执行多个get请求。

Multi-Get Request

MultiGetRequest构造函数为空,需要你添加`MultiGetRequest.Item`来配置要获取的内容:

        MultiGetRequest request = new MultiGetRequest();
request.add(new MultiGetRequest.Item(
"index", // Index
"type", // Type
"example_id")); //Document id
//再添加一个
request.add(new MultiGetRequest.Item("index", "type", "another_id"));

可选参数

get API支持的可选参数,multiGet都支持。 您可以在每一项上设置这些大部分可选参数,为什么是大部分,因为有的参数是设置在主请求上,而不是每一项上:

     //禁止获取source,默认为启用
request.add(new MultiGetRequest.Item("index", "type", "example_id")
.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE));

配置source包含指定的字段:

        String[] includes = new String[] {"foo", "*r"};
String[] excludes = Strings.EMPTY_ARRAY;
FetchSourceContext fetchSourceContext =
new FetchSourceContext(true, includes, excludes);
request.add(new MultiGetRequest.Item("index", "type", "example_id")
.fetchSourceContext(fetchSourceContext));

配置source排除指定的字段:

        String[] includes1 = Strings.EMPTY_ARRAY;
String[] excludes1 = new String[] {"foo", "*r"};
FetchSourceContext fetchSourceContext1 =
new FetchSourceContext(true, includes, excludes);
request.add(new MultiGetRequest.Item("index", "type", "example_id")
.fetchSourceContext(fetchSourceContext1));
        //配置获取指定的stored字段,要求字段在mappings中是分开存储的(stored存储的原始字段,未经过分词的)
request.add(new MultiGetRequest.Item("index", "type", "example_id")
.storedFields("foo"));
MultiGetResponse response = client.multiGet(request);
MultiGetItemResponse item = response.getResponses()[0];
//获取foo的stored字段,要求字段和mappings中是分开存储的
String value = item.getResponse().getField("foo").getValue();
       // Routing value
request.add(new MultiGetRequest.Item("index", "type", "with_routing")
.routing("some_routing"));
// Parent value
request.add(new MultiGetRequest.Item("index", "type", "with_parent")
.parent("some_parent"));
request.add(new MultiGetRequest.Item("index", "type", "with_version")
.versionType(VersionType.EXTERNAL)// Version type
.version(10123L));//Version

preference, realtime 和 refresh可以设置在主请求上,而不能设置在每项上

        request.preference("some_preference");//preference值
request.realtime(false);//将realtime标志设置为false(默认为true)
request.refresh(true);//在检索文档之前执行刷新(默认为false)

同步执行

        //构建MultiGetRequest后,您可以用multiGet来同步执行:
MultiGetResponse response1 = client.multiGet(request);

异步执行

异步执行多个get请求需要将MultiGetRequest实例和ActionListener实例传递给异步方法:

client.multiGetAsync(request, listener); //当MultiGetRequest执行完成时,ActionListener将被调用。

异步方法不会阻塞并会立即返回。 一旦请求完成,如果执行成功完成,则使用onResponse方法回调ActionListener,如果失败则使用onFailure方法。

MultiGetResponse的典型监听器如下所示:

        ActionListener<MultiGetResponse> listener = new ActionListener<MultiGetResponse>() {
@Override
public void onResponse(MultiGetResponse response) {
//执行成功完成时调用。 response以参数的形式提供。
} @Override
public void onFailure(Exception e) {
// 在失败的情况下调用。 引发的异常作为参数提供。
}
};

Multi Get Response

返回的MultiGetResponse在getResponses中包含一个MultiGetItemResponse的列表,其顺序与请求的顺序相同。 如果获取成功,MultiGetItemResponse包含GetResponse,如果失败则包含MultiGetResponse.Failure。 成功看起来就像普通的GetResponse。

   MultiGetItemResponse firstItem = response.getResponses()[0];
//assertNull(firstItem.getFailure());//getFailure返回null,由于这没有失败。
GetResponse firstGet = firstItem.getResponse();//getResponse返回GetResponse。
String index = firstItem.getIndex();
String type = firstItem.getType();
String id = firstItem.getId();
if (firstGet.isExists()) {
long version = firstGet.getVersion();
String sourceAsString = firstGet.getSourceAsString();//以字符串形式获取文档
Map<String, Object> sourceAsMap = firstGet.getSourceAsMap();//以Map <String,Object>形式获取文档
byte[] sourceAsBytes = firstGet.getSourceAsBytes();//以字节数组的形式检索文档
} else {
//处理未找到文档的方案。 请注意,虽然返回的响应具有404状态代码,但仍返回有效的GetResponse而不是抛出异常。
//此时此类响应不持有任何源文档,并且其isExists方法返回false。
     }

当其中一个子请求执行不存在的索引时,getFailure将包含异常:

            MultiGetItemResponse missingIndexItem = response.getResponses()[0];
assertNull(missingIndexItem.getResponse());//getResponse 是 null.
//getFailure不为null,并且包含Exception,该异常实际上是一个ElasticsearchException
Exception e = missingIndexItem.getFailure().getFailure();
ElasticsearchException ee = (ElasticsearchException) e;
// TODO status is broken! fix in a followup
//此时它的状态为NOT_FOUND。 要不是这是一个multi get,它其实就是一个HTTP 404。
assertEquals(RestStatus.NOT_FOUND, ee.status());
//getMessage解释了实际原因,没有这样的索引。
assertThat(e.getMessage(),containsString("reason=no such index"));

如果请求特定文档版本,并且现有文档具有不同的版本号,则会引发版本冲突:

     MultiGetRequest request2 = new MultiGetRequest();
request2.add(new MultiGetRequest.Item("index", "type", "example_id")
.version(1000L));
MultiGetResponse response2 = client.multiGet(request2);
MultiGetItemResponse item2 = response.getResponses()[0];
assertNull(item.getResponse());//getResponse 是 null.
//getFailure不为null,并且包含Exception,该异常实际上是一个ElasticsearchException
Exception e = item.getFailure().getFailure();
ElasticsearchException ee = (ElasticsearchException) e;
// TODO status is broken! fix in a followup
//此时它的状态为NOT_FOUND。 要不是这是一个multi get,它就是一个HTTP 409 。
// assertEquals(RestStatus.CONFLICT, ee.status());
//getMessage解释了实际原因,即版本冲突。
assertThat(e.getMessage(),
containsString("version conflict, current version [1] is "
+ "different than the one provided [1000]"));

官方文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-multi-get.html

Multi-Get API的更多相关文章

  1. elasticsearch6.7 05. Document APIs(8)Multi Get API

    7.Multi Get API(Multi Get API) multi GET API 允许你一次性获取多个文档,你需要指定docs数组,其中包含了所有你需要查询的文档,每个查询结构至少包含索引,类 ...

  2. elasticsearch中常用的API

    elasticsearch中常用的API分类如下: 文档API: 提供对文档的增删改查操作 搜索API: 提供对文档进行某个字段的查询 索引API: 提供对索引进行操作,查看索引信息等 查看API: ...

  3. elasticsearch中的API

    elasticsearch中的API es中的API按照大类分为下面几种: 文档API: 提供对文档的增删改查操作 搜索API: 提供对文档进行某个字段的查询 索引API: 提供对索引进行操作 查看A ...

  4. elasticsearch基本操作之--java基本操作 api

    /** * 系统环境: vm12 下的centos 7.2 * 当前安装版本: elasticsearch-2.4.0.tar.gz */ 默认进行了elasticsearch安装和ik安装, 超时配 ...

  5. ES系列四、ES6.3常用api之文档类api

    1.Index API: 创建并建立索引 PUT twitter/tweet/ { "user" : "kimchy", "post_date&quo ...

  6. elasticsearch6.7 05. Document APIs(2)Index API

    Single document APIs Index API Get API Delete API Update API Multi-document APIs Multi Get API Bulk ...

  7. Kafka:ZK+Kafka+Spark Streaming集群环境搭建(二十)ES6.2.2 Client API

    scala版本2.11 java版本1.8 spark版本2.2.1 es版本6.2.2 hadoop版本2.9.0 elasticsearch节点列表: 192.168.0.120 192.168. ...

  8. ElasticSearch Document API

    删除索引库 可以看到id为1的索引库不见了 这里要修改下配置文件 slave1,slave2也做同样的操作,在这里就不多赘述了. 这个时候记得要重启elasticseach才能生效,怎么重启这里就不多 ...

  9. Elastic Stack 笔记(八)Elasticsearch5.6 Java API

    博客地址:http://www.moonxy.com 一.前言 Elasticsearch 底层依赖于 Lucene 库,而 Lucene 库完全是 Java 编写的,前面的文章都是发送的 RESTf ...

  10. http://elasticsearch-py.readthedocs.io/en/master/api.html

    API Documentation All the API calls map the raw REST api as closely as possible, including the disti ...

随机推荐

  1. Mysql 时间差(年、月、天、时、分、秒)

    SELECT TIME_TO_SEC(TIMEDIFF('2018-09-30 19:38:45', '2018-08-23 10:13:01')) AS DIFF_SECOND1, -- 秒 UNI ...

  2. Python字符串的两种方式——百分号方式,format的方式

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...

  3. 【原创】大数据基础之Kudu(3)primary key

    关于kudu的primary key The primary key may not be changed after the table is created. You must drop and ...

  4. Bootstrap-datepicker3官方文档中文翻译---Markup/标记(原文链接 http://bootstrap-datepicker.readthedocs.io/en/latest/index.html)

    Markup/标记 下面是已经支持的标签的例子.这些标签本身不会提供DatePicker控件:你需要在标签上实例化Datepicker. input/输入框 最简单的例子: input获得焦点 (使用 ...

  5. Spring 开发常见问题

    linux 下http 接收中文参数乱码 解决: 在application.yml配置文件中添加 spring: http: encoding: charset: GB2312

  6. Java 自定义注释@interface的用法

    最简单的待校验的注解定义 @Documented @Constraint(validatedBy = ExistBlankByListValidator.class) @Target({PARAMET ...

  7. jq实现多选反选

    <script type="text/javascript">    $('input [name="ckball"]').click(functi ...

  8. Continuity of arithmetic operations

    Arithmetic operations taught in elementary schools are continuous in the high level topological poin ...

  9. docker 安装mysql

    1.安装docker 参见这个文章第一步:https://www.cnblogs.com/yanglei-xyz/p/10600707.html 2.安装mysql 查找Docker Hub上的mys ...

  10. 2018-2019 20165235 网络对抗 Exp5 MSF基础

    2018-2019 20165235 网络对抗 Exp5 MSF基础 1. 实践内容(3.5分) 1.1一个主动攻击实践 攻击方:kali 192.168.21.130 靶机: win7 192.16 ...