SpringBoot集成Elasticsearch7.4 实战(三)

51 篇文章 3 订阅
8 篇文章 2 订阅

本篇文章主要讲的是:在Springboot环境下,管理数据

1. 数据管理

1.1. 新增数据

1.1.1. 单实例新增

http方式提交数据,案例中我将数据格式做了规范,提交过程中需要指定索引名,以及JSON格式数据,这样尽可能在实际过程中做到通用。

为此我用交互对象Vo来接受前端传递来的数据,再解析该Vo,获取要提交的目标索引。

  • 后端接口实现



/**
    * @Description 新增数据
    * @param elasticDataVo
    * @return xyz.wongs.weathertop.base.message.response.ResponseResult
    * @throws
    * @date 2019/11/20 17:10
    */
@RequestMapping(value = "/add",method = RequestMethod.POST)
public ResponseResult add(@RequestBody ElasticDataVo elasticDataVo){
    ResponseResult response = getResponseResult();
    try {
        if(!StringUtils.isNotEmpty(elasticDataVo.getIdxName())){
            response.setCode(ResponseCode.PARAM_ERROR_CODE.getCode());
            response.setMsg("索引为空,不允许提交");
            response.setStatus(false);
            log.warn("索引为空");
            return response;
        }
        ElasticEntity elasticEntity = new ElasticEntity();
        elasticEntity.setId(elasticDataVo.getElasticEntity().getId());
        elasticEntity.setData(elasticDataVo.getElasticEntity().getData());

        baseElasticService.insertOrUpdateOne(elasticDataVo.getIdxName(), elasticEntity);

    } catch (Exception e) {
        response.setCode(ResponseCode.ERROR.getCode());
        response.setMsg("服务忙,请稍后再试");
        response.setStatus(false);
        log.error("插入数据异常,metadataVo={},异常信息={}", elasticDataVo.toString(),e.getMessage());
    }
    return response;
}
  • ElasticDataVo类



package xyz.wongs.weathertop.palant.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import xyz.wongs.weathertop.base.entiy.ElasticEntity;

/**
 * @ClassName ElasticDataVo
 * @Description http交互Vo对象
 * @author WCNGS@QQ.COM
 * @Github <a>https://github.com/rothschil</a>
 * @date 2019/11/21 9:10
 * @Version 1.0.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ElasticDataVo<T> {

    /**
     * 索引名
     */
    private String idxName;
    /**
     * 数据存储对象
     */
    private ElasticEntity elasticEntity;

}

  • ElasticEntity类



package xyz.wongs.weathertop.base.entiy;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import xyz.wongs.weathertop.base.persistence.mybatis.entity.BaseEntity;

import java.util.Map;

/**
 * @ClassName ElasticEntity
 * @Description  数据存储对象
 * @author WCNGS@QQ.COM
 * @Github <a>https://github.com/rothschil</a>
 * @date 2019/11/21 9:10
 * @Version 1.0.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ElasticEntity<T> {

    /**
     * 主键标识,用户ES持久化
     */
    private String id;

    /**
     * JSON对象,实际存储数据
     */
    private Map data;
}
  • Postman提交

1.1.2. 批量提交

1.2. 条件查询

为了通用,我在web端也分装了一层Vo,为了演示需要我仅写一个 match 精确匹配的查询。

  • 后端接口实现


/**
    * @Description
    * @param queryVo 查询实体对象
    * @return xyz.wongs.weathertop.base.message.response.ResponseResult
    * @throws
    * @date 2019/11/21 9:31
    */
@RequestMapping(value = "/get",method = RequestMethod.GET)
public ResponseResult get(@RequestBody QueryVo queryVo){

    ResponseResult response = getResponseResult();

    if(!StringUtils.isNotEmpty(queryVo.getIdxName())){
        response.setCode(ResponseCode.PARAM_ERROR_CODE.getCode());
        response.setMsg("索引为空,不允许提交");
        response.setStatus(false);
        log.warn("索引为空");
        return response;
    }

    try {
        Class<?> clazz = ElasticUtil.getClazz(queryVo.getClassName());
        Map<String,Object> params = queryVo.getQuery().get("match");
        Set<String> keys = params.keySet();
        MatchQueryBuilder queryBuilders=null;
        for(String ke:keys){
            queryBuilders = QueryBuilders.matchQuery(ke, params.get(ke));
        }
        if(null!=queryBuilders){
            SearchSourceBuilder searchSourceBuilder = ElasticUtil.initSearchSourceBuilder(queryBuilders);
            List<?> data = baseElasticService.search(queryVo.getIdxName(),searchSourceBuilder,clazz);
            response.setData(data);
        }
    } catch (Exception e) {
        response.setCode(ResponseCode.ERROR.getCode());
        response.setMsg("服务忙,请稍后再试");
        response.setStatus(false);
        log.error("查询数据异常,metadataVo={},异常信息={}", queryVo.toString(),e.getMessage());
    }
    return response;
}
  • QueryVo类



/** 查询Vo对象
 * @ClassName QueryVo
 * @Description 
 * @author WCNGS@QQ.COM
 * @Github <a>https://github.com/rothschil</a>
 * @date 2019/10/25 23:16
 * @Version 1.0.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class QueryVo {

    /**
     * 索引名
     */
    private String idxName;
    /**
     * 需要反射的实体类型,用于对查询结果的封装
     */
    private String className;
    /**
     * 具体条件
     */
    private Map<String,Map<String,Object>> query;
}
  • Postman提交

1.3. 删除数据

1.3.1. 单实例删除


/**
    * @Description 删除
    * @param elasticDataVo
    * @return xyz.wongs.weathertop.base.message.response.ResponseResult
    * @throws
    * @date 2019/11/21 9:56
    */
@RequestMapping(value = "/delete",method = RequestMethod.POST)
public ResponseResult delete(@RequestBody ElasticDataVo elasticDataVo){
    ResponseResult response = getResponseResult();
    try {
        if(!StringUtils.isNotEmpty(elasticDataVo.getIdxName())){
            response.setCode(ResponseCode.PARAM_ERROR_CODE.getCode());
            response.setMsg("索引为空,不允许提交");
            response.setStatus(false);
            log.warn("索引为空");
            return response;
        }
        baseElasticService.deleteOne(elasticDataVo.getIdxName(),elasticDataVo.getElasticEntity());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;

}

2.相关章节

一、SpringBoot集成Elasticsearch7.4 实战(一)

二、SpringBoot集成Elasticsearch7.4 实战(二)

三、SpringBoot集成Elasticsearch7.4 实战(三)

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot是一个快速开发框架,可以轻松地将Elasticsearch集成到你的应用程序中。下面是整合Spring BootElasticsearch 7.4的步骤: 1. 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 在application.properties文件中添加以下配置: ``` spring.data.elasticsearch.cluster-name=my-application spring.data.elasticsearch.cluster-nodes=localhost:9300 ``` 3. 创建一个ElasticsearchRepository接口,用于定义Elasticsearch的操作方法。例如: ``` public interface BookRepository extends ElasticsearchRepository<Book, String> { List<Book> findByTitle(String title); } ``` 4. 创建一个Elasticsearch的配置类,用于配置Elasticsearch的客户端。例如: ``` @Configuration public class ElasticsearchConfig { @Bean public RestHighLevelClient client() { RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http")); RestHighLevelClient client = new RestHighLevelClient(builder); return client; } @Bean public ElasticsearchRestTemplate elasticsearchTemplate() { return new ElasticsearchRestTemplate(client()); } } ``` 5. 在你的代码中使用ElasticsearchRepository接口中定义的方法来操作Elasticsearch。例如: ``` @Autowired private BookRepository bookRepository; public void searchBooks() { List<Book> books = bookRepository.findByTitle("Spring Boot"); // do something with the books } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吴名氏.

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值