0
点赞
收藏
分享

微信扫一扫

Springboot 快速集成 ES

孟佳 2024-02-02 阅读 9

 1、Springboot 官网给出的版本选择标准

2、选择版本依赖

我的 elasticsearch 服务版本为 7.17.13,所以 springboot 版本我选用 2.7.10

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.7.10</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

客户端版本选择 springboot 默认版本 

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

添加配置文件

spring:
  elasticsearch:
    uris: http://localhost:9200
    username: elastic
    password: admin123

对应的配置类:org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties

ps: spring.elasticsearch.rest 的配置方式从 springboot 2.6.0 起已弃用,将在3.0.0中移除,不推荐使用

3、实现简单的增删改查

a、继承 ElasticsearchRepository<T, ID> 接口,使用模版方法或自定义方法
@Repository
public interface SystemConfigRepository extends ElasticsearchRepository<SystemConfig, String> {

    SystemConfig findByBizAndCodeAndKey(String biz, String appCode, String ruleKey);

    @Query("{\"bool\": {\"must\": [{\"match\": {\"appCode\": \"?0\"}}," +
            "{\"match\": {\"ruleKey\": \"?1\"}}]}}")
    SystemConfig findByCondition(String appCode, String ruleKey);
}
基于命名约定
基于 @Query 注解

        在查询方法上直接指定 Elasticsearch 查询语句,可以使用 Elasticsearch 查询 DSL 编写复杂的查询逻辑,并使用 SpEL 表达式引用方法参数或其他变量。

  • 字符串查询
@Query("{\"match\": {\"field\": \"value\"}}")
List<YourEntity> findByCustomQuery();
  • 参数绑定
@Query("{\"match\": {\"field\": \"?0\"}}")
List<YourEntity> findByValue(String value);
  • 布尔查询
// 使用布尔查询可以组合多个查询条件,例如 must、should、must_not 等
@Query("{\"bool\": {\"must\": [{\"match\": {\"field1\": \"value1\"}}," +
       "{\"match\": {\"field2\": \"value2\"}}]}}")
List<YourEntity> findByCustomQuery();
  • 范围查询
@Query("{\"range\": {\"age\": {\"gte\": 18, \"lte\": 30}}}")
List<YourEntity> findByAgeRange();
  •  排序查询
@Query("{\"match_all\": {}}")
List<YourEntity> findAllByOrderByFieldAsc();
b、注入 ElasticsearchOperations 操作类
    @Resource
    private ElasticsearchOperations esOperations;

    public List<AppInfoBO> getMonitorAppList() {
        SystemConfig systemConfig = getAppInfo();
        Criteria criteria = new Criteria(SystemConfig.BIZ).is(systemConfig.getBiz())
                .and(SystemConfig.CODE).is(systemConfig.getCode())
                .and(SystemConfig.STATUS).is(systemConfig.getStatus());
        // 时间倒序
        CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
        criteriaQuery.addSort(Sort.by(Sort.Direction.DESC,SystemConfig.CREATED_TIME));
        SearchHits<SystemConfig> searchHits = esOperations.search(criteriaQuery, SystemConfig.class);
        // 转换成 map
        return searchHits.stream().map(searchHit -> {
            SystemConfig systemConfigES = searchHit.getContent();
                return new AppInfoBO(systemConfigES.getKey(), (String) systemConfigES.getValue());
        }).collect(Collectors.toList());
    }

至此执行单元测试即可完成 

举报

相关推荐

0 条评论