es文档整理1 indexapi

本文深入探讨了Elasticsearch的Index API,包括如何创建、更新和删除文档,以及设置索引元数据的关键细节。通过实例演示,阐述了如何使用Index API与Elasticsearch集群进行交互,确保数据的正确存储和检索。
package sss.first;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse; 
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.VersionType;

import org.elasticsearch.rest.RestStatus;


//https://artifacts.elastic.co/javadoc/org/elasticsearch/client/elasticsearch-rest-high-level-client/5.6.9/index.html.
//high-level-client
public class IndexApi {


//创建连接
public static RestHighLevelClient getClient(String hostname) {
//low-level-client
RestClient restClient = RestClient.builder(
        new HttpHost(hostname, 9200, "http")).build();
RestHighLevelClient client =
    new RestHighLevelClient(restClient);
return client;
}

//创建index
public static IndexRequest createIndex(int optional) throws IOException{
if (optional == 1) {
IndexRequest request = new IndexRequest(
        "posts", 
        "doc",  
        "1");   
String jsonString = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
        "}";
request.source(jsonString, XContentType.JSON);
return request;
}else if (optional == 2) {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
IndexRequest indexRequest = new IndexRequest("posts", "doc", "1")
        .source(jsonMap);
return indexRequest;
}else if (optional == 3 ) {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
    builder.field("user", "kimchy");
    builder.field("postDate", new Date());
    builder.field("message", "trying out Elasticsearch");
}
builder.endObject();
IndexRequest indexRequest = new IndexRequest("posts", "doc", "1")
        .source(builder);
return indexRequest;
}else {
IndexRequest indexRequest = new IndexRequest("posts", "doc", "1")
        .source("user", "kimchy",
                "postDate", new Date(),
                "message", "trying out Elasticsearch");
return indexRequest;
}
}

public static void optional(IndexRequest request) {
// 路由值
request.routing("routing");

// 父母的价值
request.parent("parent");

// 超时等待主分片变为可用 TimeValue
// 超时等待主分片变为可用 String
request.timeout(TimeValue.timeValueSeconds(1)); 
request.timeout("1s");

// 刷新政策作为一个WriteRequest.RefreshPolicy实例
// 刷新策略为 String
request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); 
request.setRefreshPolicy("wait_for");

// 版本号
request.version(2);

// 版本类型
request.versionType(VersionType.EXTERNAL);

// 作为DocWriteRequest.OpType值 提供的操作类型
// 提供的操作类型为String:可以是create或update(默认)
request.opType(DocWriteRequest.OpType.CREATE); 
request.opType("create");

// 索引文档之前要执行的摄取管道的名称
request.setPipeline("pipeline");
}

//同步执行
public static IndexResponse synchronizeRun(RestHighLevelClient client,IndexRequest request) throws IOException {
IndexResponse indexResponse = client.index(request);
return indexResponse;
}

//异步执行
public static IndexResponse asynchronizeRun(RestHighLevelClient client,IndexRequest request){

client.indexAsync(request, new ActionListener<IndexResponse>() {

@Override
public void onResponse(IndexResponse response) {
//执行成功完成时调用。答复是作为参数提供的 

}

@Override
public void onFailure(Exception e) {
// 在失败的情况下调用。引发的异常是作为参数提供的

}
});
return null;
}

//索引响应
public static void indexReponse(IndexResponse indexResponse) {
String index = indexResponse.getIndex();
String type = indexResponse.getType();
String id = indexResponse.getId();
long version = indexResponse.getVersion();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
//     处理(如果需要)第一次创建文档的情况

} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
//     处理(如果需要的话)文档被重写的情况,因为它已经存在

}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
//     处理成功碎片数量少于总碎片数量的情况

}
if (shardInfo.getFailed() > 0) {
    for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
        String reason = failure.reason(); 
//             处理潜在的失败
        
    }
}
}

public static void tryException(RestHighLevelClient client,IndexRequest request) throws IOException {
request = new IndexRequest("posts", "doc", "1")
        .source("field", "value")
        .version(1);
try {
    IndexResponse response = client.index(request);
} catch(ElasticsearchException e) {
    if (e.status() == RestStatus.CONFLICT) {
      //版本异常处理
   
    }
}
}

public static void tryException2(RestHighLevelClient client,IndexRequest request) throws IOException{

request = new IndexRequest("posts", "doc", "1")
        .source("field", "value")
        .opType(DocWriteRequest.OpType.CREATE);
try {
    IndexResponse response = client.index(request);
} catch(ElasticsearchException e) {
    if (e.status() == RestStatus.CONFLICT) {
//         如果opType设置为create并且具有相同索引、类型和ID的文档已存在,则会发生同样的情况:
   
    }
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值