🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 索引API ``` IndexRequest request = new IndexRequest("posts"); #1 request.id("1"); #2 String jsonString = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}"; request.source(jsonString, XContentType.JSON); #3 ``` * 1 index 索引名 * 2 document id 文档id * 3 document source 文档资源,类似于关系型数据库表的一行内容 ### source #### map ``` 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") .id("1").source(jsonMap); ``` 提供为的document source,该`Map`自动转换为JSON格式 #### XcontentBuilder ``` 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") .id("1").source(builder); ``` 作为`XContentBuilder`对象提供的文档源,Elasticsearch内置帮助器可生成JSON内容 ``` IndexRequest indexRequest = new IndexRequest("posts") .id("1") .source("user", "kimchy", "postDate", new Date(), "message", "trying out Elasticsearch"); ``` 作为`Object`key-pairs提供的文档源,被转换为JSON格式 ## 可选参数 ### 路由 ``` request.routing("routing"); ``` ### 等待primary shard超时设置 ``` request.timeout(TimeValue.timeValueSeconds(1)); //TimeValue request.timeout("1s");//string 两种方式等值 ``` ### 刷新策略 ``` request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); request.setRefreshPolicy("wait_for"); ``` ### version--版本 ``` request.version(2) ``` ### Version type ``` request.opType(DocWriteRequest.OpType.CREATE); //提供DocWriteRequest.OpType值的操作类型 request.opType("create");//以String:提供的操作类型可以是create或index(默认) ``` ### pipeline ``` request.setPipeline("pipeline"); ``` The name of the ingest pipeline to be executed before indexing the document ## Syschronous excution 同步执行 ~~~ IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); ~~~ ## Asynchronnou execution 异步执行 ~~~ client.indexAsync(request, RequestOptions.DEFAULT, listener); ~~~ A typical listener for`index`looks like: ``` listener = new ActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse indexResponse) { } @Override public void onFailure(Exception e) { } }; ``` ### Index Response ~~~ String index = indexResponse.getIndex(); String id = indexResponse.getId(); 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(); } } ~~~ 处理(如果需要)首次创建文档的情况 处理(如果需要)已存在的文档被重写的情况 处理成功分片数量少于总分片数量的情况 处理潜在的故障