一文读懂 Java操作Elasticsearch( 七 )

ElasticsearchExceptionIndexRequest request = new IndexRequest("posts").id("1").source("field", "value").setIfSeqNo(10L).setIfPrimaryTerm(20);try {IndexResponse response = client.index(request, RequestOptions.DEFAULT);} catch(ElasticsearchException e) {if (e.status() == RestStatus.CONFLICT) {//<1>}}

<1> 引发异常指示返回版本冲突错误
  • 在设置为且已存在具有相同索引和 ID 的文档的情况下,将发生相同的情况: opTypecreate
IndexRequest request = new IndexRequest("posts").id("1").source("field", "value").opType(DocWriteRequest.OpType.CREATE);try {IndexResponse response = client.index(request, RequestOptions.DEFAULT);} catch(ElasticsearchException e) {if (e.status() == RestStatus.CONFLICT) {//<1>}}
<1>引发异常指示返回版本冲突错误
  
5.2 获取Api (Get API) 
5.2.1 案例:private static void test01(){RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200)));GetRequest request = new GetRequest("student");// 为特定字段 配置源包含String[] includs = {"name","id","content"};String[] excluds = {"id"};FetchSourceContext context = new FetchSourceContext(true,includs,excluds);request.id("1").version(2).fetchSourceContext(context);try {GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);if (documentFields.isExists()) {//检索名称System.out.println(documentFields.getIndex());// 获取文档源的 Map 结果System.out.println(documentFields.getSource());// 获取源作为 MapSystem.out.println(documentFields.getSourceAsMap());// 获取源作为 bytesSystem.out.println(documentFields.getSourceAsBytes());}else {System.out.println("不错在该数据");}} catch (IOException e) {e.printStackTrace();}} 
5.2.2 获取请求
  • 需要以下参数:GetRequest
GetRequest getRequest = new GetRequest("posts", //<1>"1");//<1>
<1> 索引名称
<2> 文档 ID
 
5.2.3 可选参数
  • 可以选择提供以下参数:
request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);
禁用源检索,默认情况下启用
String[] includes = new String[]{"message", "*Date"};String[] excludes = Strings.EMPTY_ARRAY;FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);request.fetchSourceContext(fetchSourceContext);
为特定字段 配置 源包含
includes : 检索结果所包含的字段excludes : 检索结果排除的字段
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();
为特定存储字段配置检索(要求字段单独存储在映射中)
检索存储的字段(要求该字段单独存储在映射中)message
request.routing("routing");
路由值
request.preference("preference");
首选项值
request.realtime(false);
将实时标志设置为(默认情况下)falsetrue
request.refresh(true);
在检索文档之前执行刷新(默认情况下)false
request.version(2);
版本
request.versionType(VersionType.EXTERNAL);
版本类型
 
5.2.4 同步执行
  • 以下列方式执行 时,客户端将等待 返回 ,然后再继续执行代码: GetRequest GetResponse
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);