GetRequest形如:
GetRequest getRequest = new GetRequest( "posts", //Index "doc", //Type "1"); //Document id可配置参数如下:
//禁用源检索,默认开启 request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE); //配置source include字段 String[] includes = new String[]{"message", "*Date"}; String[] excludes = Strings.EMPTY_ARRAY; FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes); request.fetchSourceContext(fetchSourceContext); 配置source exclude字段 String[] includes = Strings.EMPTY_ARRAY; String[] excludes = new String[]{"message"}; FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes); request.fetchSourceContext(fetchSourceContext); //配置检索存储字段(需要在映射中存储的字段) request.storedFields("message"); GetResponse getResponse = client.get(request, RequestOptions.DEFAULT); String message = getResponse.getField("message").getValue(); //Routing value request.routing("routing"); //Parent value request.parent("parent"); //Preference value request.preference("preference"); //Set realtime flag to false (true by default) request.realtime(false); //设置在检索文档之前执行刷新(默认情况下为false) request.refresh(true); //设置Version request.version(2); //Version type request.versionType(VersionType.EXTERNAL);索引请求的异步执行需要将GetRequest实例和ActionListener实例传递给异步方法:
client.getAsync(request/*需要执行的GetRequest*/, RequestOptions.DEFAULT, listener/*执行完成之后的回调*/);异步执行不会堵塞并且立即返回,一旦完成,如果执行成功完成,则使用onResponse方法回调ActionListener,如果执行失败,则使用onFailure方法回调ActionListener。
典型的GetResponse:
ActionListener<GetResponse> listener = new ActionListener<GetResponse>() { //调用成功时回调,返回信息作为参数传入 @Override public void onResponse(GetResponse getResponse) { } //调用失败时回调,错误信息作为参数传入 @Override public void onFailure(Exception e) { } };从GetResponse获取返回的响应信息方式如下:
String index = getResponse.getIndex(); String type = getResponse.getType(); String id = getResponse.getId(); if (getResponse.isExists()) { long version = getResponse.getVersion(); //获取字符串响应 String sourceAsString = getResponse.getSourceAsString(); //获取 Map<String, Object>响应 Map<String, Object> sourceAsMap = getResponse.getSourceAsMap(); //获取byte[]响应 byte[] sourceAsBytes = getResponse.getSourceAsBytes(); } else { }如果文档没有找到,它会返回一个带有404响应码的正常GetResponse而不是抛出异常. 这样的响应不包含source,它的isExists方法返回false;
当在一个不存在的索引上操作的时候, 会返回 404 响应码和下面的 ElasticsearchException:
GetRequest request = new GetRequest("does_not_exist", "doc", "1"); try { GetResponse getResponse = client.get(request, RequestOptions.DEFAULT); } catch (ElasticsearchException e) { //文档不存在 if (e.status() == RestStatus.NOT_FOUND) { } }假如访问指定版本的文档,但是文档有一个不同的版本则会出现版本冲突异常:
try { GetRequest request = new GetRequest("posts", "doc", "1").version(2); GetResponse getResponse = client.get(request, RequestOptions.DEFAULT); } catch (ElasticsearchException exception) { //版本冲突 if (exception.status() == RestStatus.CONFLICT) { } }