springboot快速整合elaticsearch

Xukaiy發表於2020-10-31

匯入所需的jar包

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            (沒有配置start-parent需要指定版本號)
 </dependency>

配置elaticsearch配置類

@Configuration
public class ElasticSearchConfig {
   @Bean
   public RestHighLevelClient restHighLevelClient(){
       return  new RestHighLevelClient(RestClient.builder(new HttpHost("ip號",9200,"http")));
   }
}

啟動專案便可以使用了

簡單使用dome

@RestController
@RequestMapping("/blogtest/weblog")
@CrossOrigin //配置跨域
public class WeblogController {

    @Autowired
    WeblogService weblogService;
    @GetMapping("add")
    public result addWeblog(@RequestBody Weblog weblog){

        boolean save = weblogService.insertOne(weblog);
        return save?result.success():result.error();
    }
}

Service

public class WeblogServiceImpl extends ServiceImpl<WeblogMapper, Weblog> implements WeblogService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    LabelWeblogService labelWeblogService;
//批量插入(定時插入)
    public Boolean insertWeblog() {
        BulkRequest bulkRequest=new BulkRequest();
        bulkRequest.timeout("2m");
        List<Weblog> weblogs = baseMapper.selectList(null);
        weblogs.forEach(x->{
            bulkRequest.add(new IndexRequest("weblog").source(JSON.toJSONString(x), XContentType.JSON));
        });
        try{
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return  ! bulk.hasFailures();
        }catch (Exception e){
            throw new MyException();
        }

    }
    //高亮搜尋

    public List<Map<String,Object>> dataSearch(String keyword,Integer pageOne ,Integer pageEdn){
        SearchRequest request=new SearchRequest();
        SearchSourceBuilder builder=new SearchSourceBuilder();
        builder.from(pageOne);
        builder.size(pageEdn);
        //模糊查詢
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("desc",keyword);
        builder.query(matchQueryBuilder);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        request.source(builder);
        //高亮顯示
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("desc");
        highlightBuilder.preTags("<span style='color:#cccccc'>");
        highlightBuilder.postTags("</span");
        highlightBuilder.requireFieldMatch(false);
        builder.highlighter(highlightBuilder);
        List<Map<String,Object>>list=new ArrayList<>();
        //返回資料
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

          //hit屬性
            for(SearchHit hit:response.getHits().getHits()){
                Map<String, Object> result = hit.getSourceAsMap();
                //解析高亮欄位
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();

                HighlightField desc = highlightFields.get("desc");
                if(desc!=null){
                    Text[] fragments = desc.fragments();
                    String w_desc="";
                    for(Text t:fragments){
                        w_desc+=t;
                    }
                    result.put("desc",w_desc);
                }
                list.add(result);

            }
            return  list;


        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    //插入並放入搜尋引擎
    @Override
    public Boolean insertOne(Weblog weblog) {
        IndexRequest request = new IndexRequest("weblog").source(JSON.toJSONString(weblog), XContentType.JSON);
        baseMapper.insert(weblog);
        try {
            IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
           return response!=null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

這樣就可以快樂的使用es了

相關文章