ElasticsearchTemplate是spring对java api的封装
maven依赖:
org.springframework.data
spring-data-elasticsearch
3.1.8.RELEASE
spring bean配置 spring-es.xml
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
autowired注入实例:
@Autowiredprivate ElasticsearchTemplate elasticsearchTemplate;
分页查询demo:
BoolQueryBuilder boolQuery =QueryBuilders.boolQuery();if (params.get("uuid") != null && StringUtils.isNotBlank(params.get("uuid").toString())) {
boolQuery.must(QueryBuilders.matchPhraseQuery("article_id", params.get("uuid")));
}if (params.get("subject_id") != null && StringUtils.isNotBlank(params.get("subject_id").toString())) {
boolQuery.must(QueryBuilders.matchPhraseQuery("subject_id", params.get("subject_id")));
}if (params.get("title_like") != null && StringUtils.isNotBlank(params.get("title_like").toString())) {
boolQuery.must(QueryBuilders.matchPhraseQuery("title", params.get("title_like")));
}if (params.get("content_like") != null && StringUtils.isNotBlank(params.get("content_like").toString())) {
boolQuery.must(QueryBuilders.matchPhraseQuery("content", params.get("content_like")));
}
Pageable pageable= new PageRequest(Integer.parseInt(String.valueOf(params.get("start"))), Integer.parseInt(String.valueOf(params.get("limit"))),new Sort(Sort.Direction.DESC, "update_time"));
NativeSearchQuery searchQuery= newNativeSearchQueryBuilder()
.withIndices(centerIndexName)
.withTypes(centerArticleTypeName)
.withQuery(boolQuery)
.withPageable(pageable)
.build();
List maps = elasticsearchTemplate.queryForList(searchQuery, Map.class);
System.out.println(JSON.toJSONString(maps));