springboot快速集成elaticsearch

导入所需的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了

©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页