spring来管理 RestHighLevelClient
@Configuration
public class ElasticRestClientConf {
@Value("${elasticsearch.ip}")
private String ip;
@Value("${elasticsearch.port}")
private Integer port;
@Bean
public RestHighLevelClient elasticRestClient() {
return new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
}
}
简单的查询
public List<SourceLogEntity> getLog(String index, String serviceType, String startTime) {
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
//.keyword表示全字匹配
boolQueryBuilder.must(QueryBuilders.matchQuery("service_type.keyword", serviceType));
boolQueryBuilder.filter(QueryBuilders.rangeQuery("@timestamp").format(TIME_FORMAT).gte(startTime));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.sort("@timestamp", SortOrder.ASC);
searchSourceBuilder.query(boolQueryBuilder);
//默认只查询10条,设为最大值10000
searchSourceBuilder.size(10000);
SearchRequest request = new SearchRequest();
request.indices(index);
request.source(searchSourceBuilder);
try {
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
List<SourceLogEntity> logs = new ArrayList<>((int) response.getHits().getTotalHits());
for (SearchHit hit : response.getHits().getHits()) {
logs.add(SourceLogMapToEntity.convertToEntity(hit.getSourceAsMap()));
}
return logs;
} catch (Exception e) {
log.error();
}
}