1.注入es查询模板类
// 使用注解 @RequiredArgsConstructor
private final ElasticsearchRestTemplate elasticsearchRestTemplate;
2.查询示例代码
long startTime = LocalDateTime.of(totalTime.toLocalDate().minusDays(1), LocalTime.MIN).toEpochSecond(ZoneOffset.of("+8"));
long endTime = LocalDateTime.of(totalTime.toLocalDate().minusDays(1), LocalTime.MAX).toEpochSecond(ZoneOffset.of("+8"));
RangeQueryBuilder filter = QueryBuilders.rangeQuery("sendTime");
filter.gte(startTime);
filter.lte(endTime);
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
List<String> list = new ArrayList<>();
BoolQueryBuilder externalUserIdBuilder = QueryBuilders.boolQuery();
for (String externalUserId : list) {
externalUserIdBuilder.should(QueryBuilders.multiMatchQuery(externalUserId, "externalUserId", "event.externalUserId"));
}
boolQuery
.must(QueryBuilders.multiMatchQuery(dto.getOpenKfid(), "openKfId", "event.openKfId"))
.must(QueryBuilders.termsQuery("servicerGroupId", Lists.newArrayList(dto.getServicerGroupId(), 1L)))
.must(QueryBuilders.termQuery("origin", 3))
.must(externalUserIdBuilder);
NativeSearchQueryBuilder query = new NativeSearchQueryBuilder();
query.withQuery(boolQuery.filter(filter));
query.withSort(SortBuilders.fieldSort("sendTime").order(SortOrder.ASC));
SearchHits<KfMsg> hits = elasticsearchRestTemplate.search(query.build(), KfMsg.class, IndexCoordinates.of("kf_msg_" + dto.getTenantId()));
List<SearchHit<KfMsg>> searchHits = hits.getSearchHits();
log.info("查询的总条数是:{},es查询到的数据是:{}", searchHits.size(), searchHits);
for (SearchHit<KfMsg> hit : hits.getSearchHits()) {
KfMsg msg = hit.getContent();
log.info("查询到的信息是:{}", JSONObject.toJSONString(msg));
}
dto.setTotal(searchHits.size());
}
3.es,kibnan查询示例
1.查询版本及mapping信息
// 查询版本信息
GET /
// 查询索引mapping信息
GET /索引/_mapping
4.查询示例
GET /索引/_search
{
"from": 0,
"size": 20,
"query": {
"bool": {
"filter": {
"range": {
"sendTime": {
"gte": 1640534400,
"lte": 1640620800
}
}
},
"must": [
{
"query_string": {
"query": "wkDkH9EAAAUHxB7SVz3275mcse1FqQuQ",
"fields": [
"openKfId"
]
}
},
{
"query_string": {
"query": "wmDkH9EAAAySXzaU5lUSa1yYolRwuAyQ",
"fields": [
"externalUserId"
]
}
},
{
"query_string": {
"query": "936",
"fields": [
"servicerGroupId"
]
}
}
]
}
},
"sort": [
{
"sendTime": {
"order": "asc"
}
}
]
}
5.查询注意事项
如果存入的字段设置为text,则不能使用term进行查询,需要使用match进行查询
如果为字段设置了别名,则查询时使用"字段.字段别名"进行匹配查询
参考文章:
ES 修改mapping
mapping的写入与查看