Java High Level REST Client
依赖包
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.4.3</version>
</dependency>
初始化
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
Index API
IndexRequest
IndexRequest request = new IndexRequest(
"posts", //Index
"doc", //Type
"1"); //Document id
String jsonString = "{" + // Document source provided as a String
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);
提供文档源
除了上面显示的String示例之外,还可以通过其他方式提供文档源:
以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);
作为对象Object key-pairs提供的文档源,转换为JSON格式
IndexRequest indexRequest = new IndexRequest("posts", "doc", "1")
.source("user", "kimchy",
"postDate", new Date(),
"message", "trying out Elasticsearch");
可选参数,可以选择提供以下参数:
request.routing("routing");
request.parent("parent");
request.timeout(TimeValue.timeValueSeconds(1)); //等待主分片作为TimeValue可用的超时
request.timeout("1s"); //等待主要分片可用的超时
request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
request.setRefreshPolicy("wait_for");
request.version(2);
request.versionType(VersionType.EXTERNAL);
request.opType(DocWriteRequest.OpType.CREATE); //作为DocWriteRequest.OpType值提供的操作类型
request.opType("create");//以字符串形式提供的操作类型:可以创建或更新(默认)
request.setPipeline("pipeline"); 索引文档之前要执行的管道命令
同步执行
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
异步执行
The asynchronous execution of an index request requires both the IndexRequest instance and an ActionListener instance to be passed to the asynchronous method:
client.indexAsync(request, RequestOptions.DEFAULT, listener);
The IndexRequest to execute and the ActionListener to use when the execution completes
The asynchronous method does not block and returns immediately.
Once it is completed the ActionListener is called back using the onResponse method if the execution successfully completed or using the onFailure method if it failed.
A typical listener for IndexResponse looks like:
ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
//
Called when the execution is successfully completed. The response is provided as an argument
}
@Override
public void onFailure(Exception e) {
//
Called in case of failure. The raised exception is provided as an argument
}
};
Index Response
The returned IndexResponse allows to retrieve information about the executed operation as follows:
String index = indexResponse.getIndex();
String type = indexResponse.getType();
String id = indexResponse.getId();
long version = indexResponse.getVersion();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
//1
} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
//2
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
//3
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason = failure.reason(); //4
}
}
- Handle (if needed) the case where the document was created for the first time
- Handle (if needed) the case where the document was rewritten as it was already existing
- Handle the situation where number of successful shards is less than total shards
- Handle the potential failures
If there is a version conflict, an ElasticsearchException will be thrown:
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) {
//1
}
}
- The raised exception indicates that a version conflict error was returned
Same will happen in case opType was set to create and a document with same index, type and id already existed:
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) {
//1
}
}
- The raised exception indicates that a version conflict error was returned
Get API
Get Request
A GetRequest requires the following arguments:
GetRequest getRequest = new GetRequest( "posts", // Index "doc", //Type "1"); // Document id
Optional arguments 可选参数
The following arguments can optionally be provided: