elasticsearchTemplate操作es
Posted chenmz1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了elasticsearchTemplate操作es相关的知识,希望对你有一定的参考价值。
ElasticsearchTemplate是spring对java api的封装
maven依赖:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>3.1.8.RELEASE</version> </dependency>
spring bean配置 spring-es.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <elasticsearch:transport-client id="client" cluster-nodes="192.168.71.137:9300" cluster-name="large-data-transfer-platform"/> <bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <constructor-arg ref="client"/> </bean> </beans>
autowired注入实例:
@Autowired private 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 = new NativeSearchQueryBuilder() .withIndices(centerIndexName) .withTypes(centerArticleTypeName) .withQuery(boolQuery) .withPageable(pageable) .build(); List<Map> maps = elasticsearchTemplate.queryForList(searchQuery, Map.class); System.out.println(JSON.toJSONString(maps));
以上是关于elasticsearchTemplate操作es的主要内容,如果未能解决你的问题,请参考以下文章
使用 elasticsearchTemplate 从 ElasticSearch 获取所有文档
Spring Boot 自动配置覆盖自定义(elasticsearchTemplate)配置