springboot ElasticSearch 簡單的全文檢索高亮

前陣子和張三丰聊天提到了es。此次正好有機會學習並使用html

首先引入依賴node

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

配置文件spring

spring.data.elasticsearch.local=true
spring.data.elasticsearch.repositories.enabled=true
spring.data.elasticsearch.cluster-name=yourname
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300

而後 建立接口並繼承ElasticsearchRepository app

idea 類繼承 ElasticsearchRepositorydom

package com.school.service;

import com.school.model.Idea;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public interface IdeaRepository extends ElasticsearchRepository<Idea, Long> {
}

下一步在須要使用的service 或 Controller中 引用elasticsearch

@Autowired
    private IdeaRepository ideaRepository;      //esjap類

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;    //es工具

使用save方法把數據保存到es中
業務代碼忽略... 保存就完事了ide

public void save(Long ideaId) {
        // 插入數據到es中
        Idea idea = this.selectById(ideaId);
        idea.setId(ideaId);
        ideaRepository.save(idea);
    }

全文檢索並高亮數據spring-boot

這裏注意分頁的頁數是從0開始... 搞得我覺得沒查到數據debug了好久工具

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;


    @Autowired
    private IdeaRepository ideaRepository;      //esjap類

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;    //es工具


/**
     * 從es檢索數據
     *
     * @param content  搜索關鍵字
     * @param pageNum  頁
     * @param pageSzie 條
     * @return
     */
public AggregatedPage<Idea> getIdeaListBySrt(String content, Integer pageNum, Integer pageSzie) {
        Pageable pageable = PageRequest.of(pageNum, pageSzie);

        String preTag = "<font color='#dd4b39'>";//google的色值
        String postTag = "</font>";

        SearchQuery searchQuery = new NativeSearchQueryBuilder().
                withQuery(matchQuery("ideaTitle", content)).
                withQuery(matchQuery("ideaContent", content)).
                withHighlightFields(new HighlightBuilder.Field("ideaTitle").preTags(preTag).postTags(postTag),
                        new HighlightBuilder.Field("ideaContent").preTags(preTag).postTags(postTag)).build();
        searchQuery.setPageable(pageable);
        
        // 不須要高亮直接return ideas 
        // AggregatedPage<Idea> ideas = elasticsearchTemplate.queryForPage(searchQuery, Idea.class);
        
        // 高亮字段
        AggregatedPage<Idea> ideas = elasticsearchTemplate.queryForPage(searchQuery, Idea.class, new SearchResultMapper() {

            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
                List<Idea> chunk = new ArrayList<>();
                for (SearchHit searchHit : response.getHits()) {
                    if (response.getHits().getHits().length <= 0) {
                        return null;
                    }
                    Idea idea = new Idea();
                    //name or memoe
                    HighlightField ideaTitle = searchHit.getHighlightFields().get("ideaTitle");
                    if (ideaTitle != null) {
                        idea.setIdeaTitle(ideaTitle.fragments()[0].toString());
                    }
                    HighlightField ideaContent = searchHit.getHighlightFields().get("ideaContent");
                    if (ideaContent != null) {
                        idea.setIdeaContent(ideaContent.fragments()[0].toString());
                    }

                    chunk.add(idea);
                }
                if (chunk.size() > 0) {
                    return new AggregatedPageImpl<>((List<T>) chunk);
                }
                return null;
            }
        });
        return ideas;
    }

其餘基礎接口直接使用 ideaRepository. post

高亮寫法借鑑代碼地址點我
其餘方式查詢寫法地址點我

相關文章
相關標籤/搜索