RestHighLevelClient的基本使用
1. pom引入
<dependency>
<groupId>org.elasticsearchgroupId>
<artifactId>elasticsearchartifactId>
<version>6.6.1version>
<exclusions>
<exclusion>
<artifactId>jackson-coreartifactId>
<groupId>com.fasterxml.jackson.coregroupId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-high-level-clientartifactId>
<version>6.6.1version>
<exclusions>
<exclusion>
<groupId>org.elasticsearchgroupId>
<artifactId>elasticsearchartifactId>
exclusion>
exclusions>
dependency>
2. yaml配置
elasticsearch:
clientIps: 127.0.0.1
httpPort: 8990
username: test
password: 1234
esParam:
IndexName: testName
indexType: "type"
bulkSize: 500
docNum: 200000000
3. Rest客户端创建
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RestClientConfig {
@Value("${elasticsearch.clientIps}")
private String clientIps;
@Value("${elasticsearch.httpPort}")
private int httpPort;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
private HttpHost[] getHttpHosts(String clientIps, int esHttpPort) {
String[] clientIpList = clientIps.split(",");
HttpHost[] httpHosts = new HttpHost[clientIpList.length];
for (int i = 0; i < clientIpList.length; i++) {
httpHosts[i] = new HttpHost(clientIpList[i], esHttpPort, "http");
}
return httpHosts;
}
@Bean
public RestHighLevelClient restHighLevelClient() {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
return new RestHighLevelClient(RestClient.builder(getHttpHosts(clientIps, httpPort)).setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
}
}
4. 常用操作
@Component
@Data
public class AppConfig {
@Value("${esParam.indexType}")
private String indexType;
@Value("${esParam.testName}")
private String testName;
}
@Data
public class Demo {
private String name;
private Integer age ;
private String sex ;
private String grade ;
private String subject ;
private Integer score ;
private Integer offset;
private Integer pageSize;
}
@Autowired
private RestHighLevelClient restHighLevelClient;
@Autowired
private AppConfig appConfig;
public void syncData() {
List<Demo> list = dataList;
for (Demo e : list) {
Map<String, Object> map = CommUtil.objectToMap(e);
request.add(new IndexRequest(appConfig.getTestName(), appConfig.getIndexType()).source(map, XContentType.JSON));
}
try {
BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
if (response.hasFailures()) {
exceptionRetry(request, response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void exceptionRetry(BulkRequest request, BulkResponse response) {
List<DocWriteRequest<?>> list = request.requests();
BulkRequest requestRetry = new BulkRequest();
for (BulkItemResponse bir : response) {
if (bir.isFailed()) {
int docIndex = bir.getItemId();
IndexRequest ir = (IndexRequest) list.get(docIndex);
requestRetry.add(new IndexRequest(appConfig.getTestName(), appConfig.getIndexType()).source(ir.sourceAsMap(), XContentType.JSON));
}
}
try {
Thread.sleep(1000);
BulkResponse responseRetry = restHighLevelClient.bulk(requestRetry, RequestOptions.DEFAULT);
exceptionLog(requestRetry, responseRetry);
} catch (Exception e) {
log.error("ES同步重试出错!", e);
}
}
private void exceptionLog(BulkRequest request, BulkResponse response) {
List<DocWriteRequest<?>> list = request.requests();
for (BulkItemResponse bir : response) {
if (bir.isFailed()) {
int docIndex = bir.getItemId();
IndexRequest ir = (IndexRequest) list.get(docIndex);
log.error("同步重试失败reason=[{}],data=[{}]", bir.getFailureMessage(), ir.sourceAsMap().toString());
}
}
}
public void updateById(Map<String, Object> data, String indexName, String id) {
if (log.isDebugEnabled()) {
log.info("es开始更新数据:{}", JSON.toJSONString(data));
}
UpdateRequest request;
try {
request = new UpdateRequest(indexName, appConfig.getIndexType(), id).doc(data);
UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
log.info("更新状态:{}", response.getResult());
} catch (IOException e) {
log.error("更新写入异常:{}", e.getMessage(), e);
}
if (log.isDebugEnabled()) {
log.info("es更新数据完成");
}
}
public void deleteByQueryRequest(String score){
DeleteByQueryRequest delReq = new DeleteByQueryRequest(appConfig.getInstPrcsIndex());
delReq.setDocTypes(appConfig.getIndexType());
delReq.setQuery(new TermQueryBuilder("score", score));
try {
restHighLevelClient.deleteByQuery(delReq, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
log.error("ES按条件删除出错: {}", e.getMessage(), e);
}
}
public static long count(String indexName, Demo demo){
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolBuilder = makeQueryParams(demo);
sourceBuilder.query(boolBuilder);
CountRequest countRequest = new CountRequest(indexName);
countRequest.source(sourceBuilder);
CountResponse countResponse;
long count = 0L;
try {
countResponse = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
count = countResponse != null ? countResponse.getCount() : 0;
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
private BoolQueryBuilder makeQueryParams(Demo demo) {
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
if (demo.getAge() != null) {
boolQueryBuilder.must(termQuery("age", String.valueOf(demo.getAge())));
}
if (!StringUtils.isEmpty(demo.getCreateDate())) {
boolQueryBuilder.must(rangeQuery("createDate").gte(demo.getCreateDate()).format("yyyy-MM-dd"));
}
if (!StringUtils.isEmpty(demo.getName())) {
boolQueryBuilder.must(QueryBuilders.wildcardQuery("name", String.format("*%s*", demo.getName())));
}
return boolQueryBuilder;
}
private List<Demo> getListFromEs(String indexName, Demo demo) {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
SearchRequest request = new SearchRequest(index);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(makeQueryParams(demo));
sourceBuilder.from(demo.getOffset()).size(demo.getPageSize());
sourceBuilder.sort("age", SortOrder.DESC);
request.source(sourceBuilder);
SearchHit[] hits = new SearchHit[0];
try {
hits = restHighLevelClient.search(request, RequestOptions.DEFAULT).getHits().getHits();
} catch (Exception e) {
log.error("ES查询出错: {}", e.getMessage(), e);
}
List<Demo> data = new ArrayList<>();
for (SearchHit hit : hits) {
data.add(gson.fromJson(hit.getSourceAsString(), Demo.class));
}
return data;
}