Springboot整合Elasticsearch7,分页高亮查询

Posted 蒙面侠1024

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot整合Elasticsearch7,分页高亮查询相关的知识,希望对你有一定的参考价值。

Springboot项目引入依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

查看maven看es的版本再去官网下载,下图为7.6.2版本

ES官网下载连接
打开链接,选择对应的版本,点击Download

点击WINDOWS下载压缩包

下载好压缩包,解压到你的目录,去githud下载对应版本的中文分词器
链接直达

点击下载zip即可

下载完成后,将分词器压缩包解压到es的plugins目录下

将bin目录的路径配置到电脑的环境变量


点击bin目录下的elasticsearch.bat启动,每次使用都需要提前启动

配置
写一个类,继承AbstractElasticsearchConfiguration类,重写elasticsearchClient()方法,ES的默认端口是9200

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

public class RestClientConfig extends AbstractElasticsearchConfiguration 

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() 

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();

        return RestClients.create(clientConfiguration).rest();
    


在给要搜索的实体类加几个注解

@Document(indexName = "discusspost")
public class DiscussPost implements Serializable 

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    @Id
    private Integer id;

    private Integer userId;

//需要搜索的字段
    @Field(analyzer = "ik_max_word",searchAnalyzer = "ik_smart")
    private String title;
//需要搜索的字段
    @Field(analyzer = "ik_max_word",searchAnalyzer = "ik_smart")
    private String content;

    @Field(type = FieldType.Integer)
    private Integer type;


    @Field(type = FieldType.Integer)
    private Integer status;

    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date createTime;

    @Field(type = FieldType.Integer)
    private Integer commentCount;

    @Field(type = FieldType.Double)
    private Double score;


删除和保存更新,需要注入bean

@Autowired 
private ElasticsearchRepository discussRepository;

保存/更新api

discussRepository.save(post);

删除api


discussRepository.deleteById(id);

查询方法,旧版的是另一个,以下查询方法,通过key,进行分页查询

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
	public List<DiscussPost> searchDiscussPost(String keyword, int current, int limit) throws IOException 
	    //查询的字段
        BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("content",keyword))
                .should(QueryBuilders.matchQuery("title",keyword));
        //构建高亮查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
        			//排序
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .withQuery(boolQueryBuilder)
                //分页
                .withPageable(PageRequest.of(current, limit))
                .withHighlightFields(
                        new HighlightBuilder.Field("title"),
                        new HighlightBuilder.Field("content")
                        )
                  //高亮
                .withHighlightBuilder(new HighlightBuilder().preTags("<em>").postTags("</em>"))
                .build();
        //查询
        SearchHits<DiscussPost> search = elasticsearchTemplate.search(searchQuery, DiscussPost.class);
        //得到查询返回的内容
        List<org.springframework.data.elasticsearch.core.SearchHit<DiscussPost>> searchHits = search.getSearchHits();
        //设置一个最后需要返回的实体类集合
        List<DiscussPost> posts = new ArrayList<>();
        //遍历返回的内容进行处理
        for(SearchHit<DiscussPost> searchHit:searchHits)
            //高亮的内容
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
            //将高亮的内容填充到content中
            searchHit.getContent().setTitle(highlightFields.get("title")==null ? searchHit.getContent().getTitle():highlightFields.get("title").get(0));
            searchHit.getContent().setContent(highlightFields.get("content")==null ? searchHit.getContent().getContent():highlightFields.get("content").get(0));
            //放到实体类中
            posts.add(searchHit.getContent());
        
        return posts;
    

以上是关于Springboot整合Elasticsearch7,分页高亮查询的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot 整合 Elasticsearch 实现海量级数据搜索

Springboot 2.5.x整合ElasticSearch 7.1x

SpringBoot检索篇Ⅳ --- 整合ElasticSearch

SpringBoot整合ElasticSearch7.x及实战

[ ElasticSearch ] SpringBoot整合ElasticSearch

[ ElasticSearch ] SpringBoot整合ElasticSearch