Windows下SpringBoot引入ElasticSearch

安装与配置

0、版本问题

版本不一致可能出现莫名奇妙的问题。比如:

  • ElasticSearch和IK版本不一致,ElasticSearch启动失败。
  • elasticsearch-rest-high-level-client和ElasticSearch版本不一致,创建Index失败。

ElasticSearch Client从7.0开始推荐使用elasticsearch-rest-high-level-client。可以在pom.xml的Dependency Analyzer中查看对应依赖的版本。

alt

SpringBoot elasticsearch-rest-high-level-client ElasticSearch IK
2.5.5 7.12.1 7.12.1 7.12.1

1、下载

  • ElasticSearch

    • 本次下载的是V7.12.1。
    • 解压
  • IK(中文分词插件,不需要则不用下载)

    • 本次下载的是V7.12.1。

    • 在ElasticSearch目录中的plugins目录下,创建IK目录,并将IK包解压到IK目录下。

      alt

2、配置

  • 环境变量配置

    • 环境变量的Path变量中,添加ElasticSearch中bin目录的路径。

      D:\XiangWorkingSpace\elasticsearch-7.12.1\bin
      
  • ElasticSearch配置:修改配置文件:config/elasticsearch.yml

    cluster.name: 你的自定义目录
    path.data: 你的自定义目录
    path.logs: 你的自定义目录
  • 启动
    • 进入bin目录,双击elasticsearch.bat即可。

SpringBoot整合ElasticSearch

  • 引入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    
  • 配置ElasticSearch

    @Configuration
    public class ElasticSearchConfig {
        @Value("${elasticsearch.host.one:localhost:9200}")
        private String hostOne;
        @Bean
        RestHighLevelClient client() {
            ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                    .connectedTo(hostOne)
                    .withConnectTimeout(Duration.ofSeconds(5))
                    .withConnectTimeout(Duration.ofSeconds(3))
                    .build();
            return RestClients.create(clientConfiguration).rest();
        }
    }
    
  • 配置实体类(Mapping Annotation Overview

    @Document(indexName = "discussPost")
    public class DiscussPost {
        @Id
        private int id;
        @Field(type = FieldType.Integer)
        private int userId;
        @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
        private String title;
        @Transient
        private String content;// 不存入ES
        ...
    }
    
  • 配置DAO

    @Repository
    	public interface ElasticSearchRepository extends ElasticsearchRepository<DiscussPost, Integer> {
    }
    

    通过ElasticSearchRepository对ES中的数据进行CURD操作。

  • 分页查询ES

@Resource
private ElasticsearchRestTemplate elasticsearchRestTemplate;
...
// 构建查询
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
    .withQuery(QueryBuilders.multiMatchQuery(keyWord, "title", "content"))
    .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
    .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
    // 页码从0开始
    .withPageable(PageRequest.of(pageNum - 1, pageSize))
    .withHighlightFields(
        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
    ).build();
// 查询
SearchHits<DiscussPost> searchHits = elasticsearchRestTemplate.search(searchQuery, DiscussPost.class);
// 遍历查询结果做一些自定义处理
for (SearchHit<DiscussPost> searchHit : searchHits.getSearchHits()) {
  DiscussPost discussPost = searchHit.getContent();
  ...
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务