很多时候需要利用java api读取Elasticsearch. 目前官方首推的是RestHighLevelClient. 所以可以尝试使用这个客户端进行简单的语句生成和操作.
首先在Maven的pom中添加dependency
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.1</version>
</dependency>
之后, 在java中可以直接写入一下代码. 创建client,指定2个端口,具体原因不知道.但是官方文档中有参考.
我才用的是 boolQueryBuilder,生成2个filter的效果. 做了范围查询和关键词匹配. filter不需要计算成绩,性能好点.
设置了fetchSource,这样只会include指定的field,减少返回数据.
rangeQuery可以用于数值和时间段查询
RestHighLevelClient client = new RestHighLevelClient(RestClient
.builder(new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")));
SearchRequest searchRequest = new SearchRequest("all_indices");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.fetchSource(new String[] {"date_search", "message"}, new String[] {});
// searchSourceBuilder.from(0).size(1);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.filter(QueryBuilders.termQuery("tags", "exception_text"));
boolQueryBuilder.filter(QueryBuilders.rangeQuery("date_search").gte("now-1d/d").lte("now/d"));
searchSourceBuilder.query(boolQueryBuilder);
searchRequest.source(searchSourceBuilder);
try {
SearchResponse rp = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = rp.getHits();
hits.forEach(test -> {
Map<String, Object> sourceAsMap = test.getSourceAsMap();
String message = (String) sourceAsMap.get("message");
});
client.close();
client = null;
} catch (IOException e) {
e.printStackTrace();
}
最后生成的dsl类似:
{
"query": {
"bool": {
"filter": [
{
"term": {
"tags": {
"value": "exception_text",
"boost": 1
}
}
},
{
"range": {
"date_search": {
"from": "now-1d/d",
"to": "now/d",
"include_lower": true,
"include_upper": true,
"boost": 1
}
}
}
],
"adjust_pure_negative": true,
"boost": 1
}
},
"_source": {
"includes": [
"date_search",
"message"
],
"excludes": [ ]
}
}