springboot ElasticSearch simple full text search highlights

Keywords: Java ElasticSearch Spring Google

I talked with Zhang Sanfeng about es a few days ago. This is a chance to learn and use

Introduce dependency first

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

configuration file

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

Then create the interface and inherit from ElasticsearchRepository

idea class inherits ElasticsearchRepository

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> {
}

The next step is to reference in the service or Controller to be used

    @Autowired
    private IdeaRepository ideaRepository;      //Class esjap

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;    //es tools

Using save method to save data to es
Business code ignore... Save it

public void save(Long ideaId) {
        // Insert data into es
        Idea idea = this.selectById(ideaId);
        idea.setId(ideaId);
        ideaRepository.save(idea);
    }

Full text search and highlight data

Notice here that the page number starts from 0... I didn't think I found the data debug for a long time

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;      //Class esjap

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;    //es tools


/**
     * Retrieving data from es
     *
     * @param content  Search keywords
     * @param pageNum  page
     * @param pageSzie strip
     * @return
     */
public AggregatedPage<Idea> getIdeaListBySrt(String content, Integer pageNum, Integer pageSzie) {
        Pageable pageable = PageRequest.of(pageNum, pageSzie);

        String preTag = "<font color='#Dd4b39 '"; / / Google's color value
        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 without highlighting 
        // AggregatedPage<Idea> ideas = elasticsearchTemplate.queryForPage(searchQuery, Idea.class);
        
        // Highlight field
        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;
    }

Other basic interfaces directly use the idea repository

Highlight code address Point me
Other ways to query write address Point me

Posted by infernon on Mon, 09 Dec 2019 00:44:19 -0800