spring整合Elasticsearch
Posted 晓宜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring整合Elasticsearch相关的知识,希望对你有一定的参考价值。
• 引入依赖
- spring-boot-starter-data-elasticsearch
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
• 配置Elasticsearch
解决netty启动冲突问题
@PostConstruct
public void init()
// 解决netty启动冲突问题
// see Netty4Utils.setAvailableProcessors()
System.setProperty("es.set.netty.runtime.available.processors", "false");
- cluster-name、cluster-nodes
# ElasticsearchProperties
spring.data.elasticsearch.cluster-name=nowcoder
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
• Spring Data Elasticsearch
Elasticsearch有两种方式可以调用:
- ElasticsearchTemplate
案例:
@Test
public void testSearchByTemplate()
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.multiMatchQuery("互联网寒冬", "title", "content"))
.withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
.withPageable(PageRequest.of(0, 10))
.withHighlightFields(
new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
).build();
Page<DiscussPost> page = elasticTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper()
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable)
SearchHits hits = response.getHits();
if (hits.getTotalHits() <= 0)
return null;
List<DiscussPost> list = new ArrayList<>();
for (SearchHit hit : hits)
DiscussPost post = new DiscussPost();
String id = hit.getSourceAsMap().get("id").toString();
post.setId(Integer.valueOf(id));
String userId = hit.getSourceAsMap().get("userId").toString();
post.setUserId(Integer.valueOf(userId));
String title = hit.getSourceAsMap().get("title").toString();
post.setTitle(title);
String content = hit.getSourceAsMap().get("content").toString();
post.setContent(content);
String status = hit.getSourceAsMap().get("status").toString();
post.setStatus(Integer.valueOf(status));
String createTime = hit.getSourceAsMap().get("createTime").toString();
post.setCreateTime(new Date(Long.valueOf(createTime)));
String commentCount = hit.getSourceAsMap().get("commentCount").toString();
post.setCommentCount(Integer.valueOf(commentCount));
// 处理高亮显示的结果
HighlightField titleField = hit.getHighlightFields().get("title");
if (titleField != null)
post.setTitle(titleField.getFragments()[0].toString());
HighlightField contentField = hit.getHighlightFields().get("content");
if (contentField != null)
post.setContent(contentField.getFragments()[0].toString());
list.add(post);
return new AggregatedPageImpl(list, pageable,
hits.getTotalHits(), response.getAggregations(), response.getScrollId(), hits.getMaxScore());
);
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
System.out.println(page.getNumber());
System.out.println(page.getSize());
for (DiscussPost post : page)
System.out.println(post);
- ElasticsearchRepository
首先写一个接口扩展 ElasticsearchRepository
@Repository
public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost, Integer>
这里我们可以直接调用相关接口实现增删改查的功能
案例:
@Test
public void testInsert()
for(int i = 109; i <= 280; i++)
discussRepository.save(discussMapper.selectDiscussPostById(i));
@Test
public void testInsertList()
discussRepository.saveAll(discussMapper.selectDiscussPosts(101, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(102, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(103, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(111, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(112, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(131, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(132, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(133, 0, 100, 0));
discussRepository.saveAll(discussMapper.selectDiscussPosts(134, 0, 100, 0));
@Test
public void testUpdate()
DiscussPost post = discussMapper.selectDiscussPostById(231);
post.setContent("我是新人,使劲灌水.");
discussRepository.save(post);
@Test
public void testDelete()
discussRepository.deleteById(319);
discussRepository.deleteById(320);
discussRepository.deleteById(321);
// discussRepository.deleteAll();
@Test
public void testSearchByRepository()
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.multiMatchQuery("互联网寒冬", "title", "content"))
.withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
.withPageable(PageRequest.of(0, 10))
.withHighlightFields(
new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
).build();
// elasticTemplate.queryForPage(searchQuery, class, SearchResultMapper)
// 底层获取得到了高亮显示的值, 但是没有返回.
Page<DiscussPost> page = discussRepository.search(searchQuery);
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
System.out.println(page.getNumber());
System.out.println(page.getSize());
for (DiscussPost post : page)
System.out.println(post);
以上是关于spring整合Elasticsearch的主要内容,如果未能解决你的问题,请参考以下文章