Springboot整合elasticsearch

springboot 整合elasticsearch 的两种实现方式

先引入es的依赖

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

java 操作es 的两种方式
一种是方便用于操作对象的,需要一个接口继承ElasticsearchRepository<bean,String>
另一种主要用于高亮查询,灵活度更高,但操作对象需要格式转换,需要一个类继承AbstractElasticsearchConfiguration类,重写elasticsearchClient方法。

继承ElasticsearchRepository<bean,String>

public interface NewsRepository extends ElasticsearchRepository<News,Integer> {

}

News 为实体类,Integer 为id类型

继承AbstractElasticsearchConfiguration

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration build = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();

        return RestClients.create(build).rest();
    }
}

代码中只需要通过@Autowired注入即可

ElasticsearchRepository示例

 @Autowired
    private StuRepository stuRepository;


    // 新增和修改  有id就是修改
    @Test
    public void testSave(){
        Stu stu = new Stu();
        stu.setId(UUID.randomUUID().toString());
        stu.setName("吴离");
        stu.setAge("24");
        stu.setBir(new Date());
        stu.setContent("springboot 整合 elasticsearch");
        Stu save = stuRepository.save(stu);
        System.out.println(save);
    }

    // 根据id删除
    @Test
    public void testDelete(){
        stuRepository.deleteById("c3cc7b71-8df2-4c25-a8cc-fcfe0c74348c");
    }

    // 删除所有
    @Test
    public void testDeleteAll(){
        stuRepository.deleteAll();
    }

    // 检索一条文档
    @Test
    public void testSearch(){
        Optional<Stu> byId = stuRepository.findById("59aebdad-3a5f-4bec-b95b-d20043d0e59d");
        System.out.println(byId.get());
    }

继承AbstractElasticsearchConfiguration

 public CommonResult findOrEs(String name) throws IOException {
        SearchRequest searchRequest = new SearchRequest("news");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 对输入的关键字进行多字段查询
        searchSourceBuilder.query(QueryBuilders.multiMatchQuery(name,"content","title"));
        // 设置高亮查询
        searchSourceBuilder.highlighter(new HighlightBuilder().field("*").requireFieldMatch(false)
                    .preTags("<span style='color:red'>")
                    .postTags("</span>"));
        // 设置查询条件
        SearchRequest source = searchRequest.source(searchSourceBuilder);
        // 执行查询
        SearchResponse searchResponse = restHighLevelClient.search(source, RequestOptions.DEFAULT);

        List<News> list  = new ArrayList<>();
        // 封装数据
        if (searchResponse.getHits().getTotalHits().value>0){

            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits){
                // 原始数据
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();

                News news = new News();

                // id
                news.setId(Integer.parseInt(hit.getId()));
                // title
                news.setTitle(sourceAsMap.get("title").toString());
                if (highlightFields.containsKey("title")){
                    news.setTitle(highlightFields.get("title").fragments()[0].toString());
                }
                // content
                news.setContent(sourceAsMap.get("content").toString());
                if (highlightFields.containsKey("content")){
                    news.setContent(highlightFields.get("content").fragments()[0].toString());
                }
                // type
                news.setType(sourceAsMap.get("type").toString());
                // time
                news.setTime(sourceAsMap.get("time").toString());
                // status
                news.setStatus(Integer.parseInt(sourceAsMap.get("status").toString()));

                list.add(news);
            }
        }
        return CommonResult.success(list);
    }

实体类示例

@Document(indexName = "news")
public class News {

    @Id
    @ApiModelProperty(value = "新闻id")
    private Integer id;

    @Field(type = FieldType.Text,analyzer = "ik_max_word")
    @ApiModelProperty(value = "新闻标题")
    private String title;

    @Field(type = FieldType.Keyword)
    @ApiModelProperty(value = "新闻类型")
    private String type;

    @Field(type = FieldType.Text,analyzer = "ik_max_word")
    @ApiModelProperty(value = "新闻内容")
    private String content;

//    @Field(type = FieldType.Date,format = DateFormat.date_time)
    @ApiModelProperty(value = "新闻时间")
    private String time;

    @Field(type = FieldType.Keyword)
    @ApiModelProperty(value = "新闻状态")
    private Integer status;

    @Field(type = FieldType.Keyword)
    @ApiModelProperty(value = "新闻图片")
    private String img;

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值