Elasticsearch java api 6.6 Document APIs(1) Index API

Index API

index 要求

创建索引需要以下参数:

Index

Type

Document id

Document source provided as a String

IndexRequest request = new IndexRequest(
        "posts", 
        "doc",  
        "1");   
String jsonString = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
        "}";
request.source(jsonString, XContentType.JSON); 

提供文档方式

以Map形式提供的文档源,该Map将自动转换为JSON格式

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);

文档源作为XContentBuilder对象提供,Elasticsearch内置助手生成JSON内容

XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
    builder.field("user", "kimchy");
    builder.timeField("postDate", new Date());
    builder.field("message", "trying out Elasticsearch");
}
builder.endObject();
IndexRequest indexRequest = new IndexRequest("posts", "doc", "1")
        .source(builder);

作为 IndexRequest 对象键对提供的文档源,它被转换为JSON格式

IndexRequest indexRequest = new IndexRequest("posts", "doc", "1")
        .source("user", "kimchy",
                "postDate", new Date(),
                "message", "trying out Elasticsearch"); 

可选参数

可以选择提供以下参数:

Routing valuerequest.routing("routing");路由
Parent valuerequest.parent("parent");添加父节点
Timeout to wait for primary shard to become available as a TimeValuerequest.timeout(TimeValue.timeValueSeconds(1));

 

等待主分片可用状态的超时

 

Timeout to wait for primary shard to become available as a Stringrequest.timeout("1s");
Refresh policy as a WriteRequest.RefreshPolicy instancerequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); 刷新机制
Refresh policy as a Stringrequest.setRefreshPolicy("wait_for"); 
Version request.version(2);设置版本
Version typerequest.versionType(VersionType.EXTERNAL);使用外部系统的版本版本类型
Operation type provided as an DocWriteRequest.OpType valuerequest.opType(DocWriteRequest.OpType.CREATE); 提供的操作类型
Operation type provided as a String: can be create or update (default)request.opType("create"); 
The name of the ingest pipeline to be executed before indexing the documentrequest.setPipeline("pipeline"); 索引文档之前要执行的摄取管道的名称

同步操作插入文档

当以下列方式执行索引请求时,客户端在继续执行代码之前等待返回索引响应:

IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

     同步调用可能会抛出IOException,以防在高级REST客户机中解析REST响应失败、请求超时或类似情况下没有响应从服务器返回。

     在服务器返回4xx或5xx错误代码的情况下,高级客户端尝试解析响应体错误细节,然后抛出一个通用的ElasticsearchException并将原始的ResponseException作为一个被抑制的异常添加到它。

异步操作插入文档

以异步方式执行索引请求,以便客户机可以直接返回。用户需要指定响应或潜在故障将如何处理,通过传递请求和侦听器到异步索引方法:

  执行索引请求和在执行完成时使用的ActionListener

client.indexAsync(request, RequestOptions.DEFAULT, listener);

      异步方法不会阻塞并立即返回。一旦执行完成,ActionListener将使用onResponse方法(如果执行成功)被调用,或者使用onFailure方法(如果执行失败)被调用。失败场景和预期的异常与同步执行情况相同。

索引的监听器如下:

listener = new ActionListener<IndexResponse>() {
    @Override
    public void onResponse(IndexResponse indexResponse) {
        //当执行成功完成时调用。
    }

    @Override
    public void onFailure(Exception e) {
        //当整个索引请求失败时调用。
    }
};

返回的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(); 
    }
}

如果存在版本冲突,将抛出ElasticsearchException:

IndexRequest request = new IndexRequest("posts", "doc", "1")
        .source("field", "value")
        .version(1);
try {
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
} catch(ElasticsearchException e) {
    if (e.status() == RestStatus.CONFLICT) {
        //引发的异常表明返回了版本冲突错误
    }
}

如果将opType设置为create,并且已经存在索引、类型和id相同的文档,则会发生相同的情况:

IndexRequest request = new IndexRequest("posts", "doc", "1")
        .source("field", "value")
        .opType(DocWriteRequest.OpType.CREATE);
try {
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
} catch(ElasticsearchException e) {
    if (e.status() == RestStatus.CONFLICT) {
        //引发的异常表明返回了版本冲突错误
    }
}

实例

Client实例创建

public class ESHighClient {
    public RestHighLevelClient getClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("test1", 9200, "http"),
                        new HttpHost("test2", 9200, "http"),
                        new HttpHost("test3", 9200, "http")
                )
        );

        return  client;
    }
    public  void closeClient(RestHighLevelClient client){
        try {
            if(client != null){
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

API测试

public class ESserviceTest {
    public static void main(String[] args) {
        final ESHighClient esHighClient = new ESHighClient();
        final RestHighLevelClient client = esHighClient.getClient();
        final ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
            @Override
            public void onResponse(IndexResponse indexResponse) {
                System.out.println("listener Status "+indexResponse.status().getStatus()
                        + "-ID-"+indexResponse.getId()
                        +"-Index-"+indexResponse.getIndex()
                        +"-Type-"+indexResponse.getType()
                        +"-Result-"+indexResponse.getResult()
                        +"-ShardInfo- "+indexResponse.getShardInfo().toString()
                        +"-Version-"+indexResponse.getVersion());
                esHighClient.closeClient(client);
            }

            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
                esHighClient.closeClient(client);
            }
        };

        try {
            final IndexRequest indexRequest = putRecord();
//            final IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
            client.indexAsync(indexRequest, RequestOptions.DEFAULT, listener);

            final RequestOptions aDefault = RequestOptions.DEFAULT;
            final List<Header> headers = aDefault.getHeaders();
            for (Header h :headers){
                System.out.println("header name= "+h.getName() +"; header value=" +h.getValue() +" ;header elements =" +h.getElements().toString());
            }
//            System.out.println(index.status());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

//            esHighClient.closeClient(client);
        }
    }

    public static IndexRequest putRecord() throws IOException{
        //Map结构生成JSON
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("user", "kimchy");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "trying out Elasticsearch");
        //
        XContentBuilder builder = XContentFactory.jsonBuilder();

        builder.startObject();
        {
            builder.field("user", "kimchy");
            builder.timeField("postDate", new Date());
            builder.field("message", "trying out Elasticsearch");
        }
        builder.endObject();
        IndexRequest indexRequest1 = new IndexRequest("posts", "doc", "1")
                .source(jsonMap);
        IndexRequest indexRequest2 = new IndexRequest("posts", "doc", "2")
                .source(builder);
        IndexRequest indexRequest3 = new IndexRequest("posts", "doc", "3")
                .source("user", "kimchy",
                        "postDate", new Date(),
                        "message2", "trying out Elasticsearch2");

//        indexRequest3.versionType(VersionType.EXTERNAL);
//        indexRequest3.version(3);

        return indexRequest3;
    }
}

原文:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high-document-index.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值