小秦哥 发表于 2025-3-2 16:25:18

SpringBoot中easy-es入门实战(最完整-结合官方文档版)

媒介:本文主要是参考官方文档举行编写,记录一下自己一些比较常利用easy-es利用方法和内容,其实他的利用和MybatisPlus差不多的,之前我还写了一些关于es的博客可以参考一下:
Springboot中利用Elasticsearch(部署+利用+讲解 最完整)_spring boot elasticsearch-CSDN博客文章欣赏阅读5.3k次,点赞29次,收藏51次。最完整最具体的springboot中利用es,在前面有服务器部署es相干的东西,在后面有利用java的实战,对于实战的方法利用结合官网深度去研究和讲解。在这篇文章前面是实战,后面是具体讲解~~~假如只想实战就只看一和二,深入了解就继续看,在将来还会继续更新对这个实战,另有es技术的更新,几万字大长文。_spring boot elasticsearchhttps://g.csdnimg.cn/static/logo/favicon32.icohttps://blog.csdn.net/qq_73440769/article/details/141477177?spm=1001.2014.3001.5501
目录
一、官方文档
二、添加依赖
三、设置
四、Spring Boot 启动类
五、准备实体类
六、编写Mapper类
七、编写接口举行CRUD
1.创建索引
2.批量新增文档数据
3.批量删除
4.修改
5.查询
普通写法:
链式写法:
时间范围查询:
八、四大嵌套查询
ES四大嵌套查询
ES四大拼接查询
官方文档案例
九、链式调用
十、MySQL和EE语法对比
一、官方文档

简介 | Easy-Es傻瓜级ElasticSearch搜刮引擎ORM框架https://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.easy-es.cn/pages/7ead0d/#%E7%AE%80%E4%BB%8Bhttps://i-blog.csdnimg.cn/direct/4f605144cec44c6e8614055ec700bcfe.png
二、添加依赖

我的项目版本是


[*] JDK:17
[*] SpringBoot:3.2.4
[*] elasticsearch:7.14.0
[*] easy-es:2.0.0
[*] mybatis:3.0.3
[*] mybatis-plus:3.5.5
[*] mysql-connector-j:8.2.0
其实在这次演示中mysql相干是没有效到的
https://i-blog.csdnimg.cn/direct/935fe97d406f4d1595738d6088438587.png
      <!-- 排除springboot中内置的es依赖,以防和easy-es中的依赖冲突-->
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                  <groupId>org.elasticsearch.client</groupId>
                  <artifactId>elasticsearch-rest-high-level-client</artifactId>
                </exclusion>
                <exclusion>
                  <groupId>org.elasticsearch</groupId>
                  <artifactId>elasticsearch</artifactId>
                </exclusion>
            </exclusions>
      </dependency>
      <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.14.0</version>
      </dependency>
      <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.14.0</version>
      </dependency>

      <dependency>
            <groupId>org.dromara.easy-es</groupId>
            <artifactId>easy-es-boot-starter</artifactId>
            <!--这里Latest Version是指最新版本的依赖,比如2.0.0,可以通过下面的图片获取-->
            <version>2.0.0</version>
      </dependency>
      <!--数据库驱动-->
      <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.2.0</version>
      </dependency>
      <!--mybatis的起步依赖-->
      <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.3</version>
      </dependency>

      <!--mybatisPlus的起步依赖-->
      <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.5</version>
      </dependency> 三、设置

https://i-blog.csdnimg.cn/direct/203f5f0e253849f4a0a4d7169add20a9.png
server:
port: 8080

spring:
profiles:
    active: dev
main:
    allow-circular-references: true
datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    #连接数据库的用户名
    url: jdbc:mysql://localhost:3306/document?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true
    username: root
    password: 123456

easy-es:
enable: true #默认为true,若为false则认为不启用本框架
address : localhost:9200 # es的连接地址,必须含端口 若为集群,则可以用逗号隔开 例如:127.0.0.1:9200,127.0.0.2:9200

logging:
level:
    tracer: trace # 设置日志级别为trace,开发时可开启以打印ES全部请求信息及DSL语句 四、Spring Boot 启动类

https://i-blog.csdnimg.cn/direct/298b6ea9999e4ceaa3bd341442f60c75.png
import org.dromara.easyes.starter.register.EsMapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EsMapperScan("com.bluefoxyu.easyes.sample.mapper")
public class Application {

    public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
    }

} 五、准备实体类

https://i-blog.csdnimg.cn/direct/264793223a77471ba48107916ae2861a.png
@Data
@IndexName(value = "document")
public class Document {
    /**
   * es对应主键id标识,自定义es中的id为我提供的id
   */
    @TableId
    @IndexId(type = IdType.CUSTOMIZE)
    private String id;
    /**
   * 文档标题,分析:IK_MAX_WORD,查找:IK_SMART
   */
    @IndexField(fieldType = FieldType.TEXT,analyzer = Analyzer.IK_MAX_WORD,searchAnalyzer = Analyzer.IK_SMART)
    private String title;
    /**
   * 文档内容,分析:IK_MAX_WORD,查找:IK_SMART
   */
    @IndexField(fieldType = FieldType.TEXT,analyzer = Analyzer.IK_MAX_WORD,searchAnalyzer = Analyzer.IK_SMART)
    private String content;

    private LocalDateTime createTime;

} 注意:


[*]String类型默认会被EE创建为keyword类型,keyword类型支持准确查询等
[*]如需分词查询,可像上面content一样,在字段上加上@IndexField注解并指明字段类型为text,并指定分词器
六、编写Mapper类

https://i-blog.csdnimg.cn/direct/b264672515a04c81880e57eae5304d3b.png
import com.bluefoxyu.easyes.sample.domain.Document;
import org.dromara.easyes.core.kernel.BaseEsMapper;

public interface DocumentMapper extends BaseEsMapper<Document> {
} 七、编写接口举行CRUD

   这里一些提示方法案例都来源于官方文档,这里只是作为一次演示和条记
数据CRUD | Easy-Es傻瓜级ElasticSearch搜刮引擎ORM框架https://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.easy-es.cn/pages/f3ee10/
https://i-blog.csdnimg.cn/direct/93c99674bef149f784f3b580f61543e1.png
1.创建索引

documentMapper.createIndex()
documentMapper.deleteIndex() https://i-blog.csdnimg.cn/direct/a30bf50fcbcf49debb1b99ce2801091b.png
    @PostMapping("/createIndex")
    public Boolean createIndex() {
      // 1.初始化-> 创建索引(相当于mysql中的表)
      return documentMapper.createIndex();
    } https://i-blog.csdnimg.cn/direct/cd9709636c0e4adc95efb7a699c48e56.png
在kibana中可以看到时间类型是利用"yyyy-MM-dd HH:mm:ss"这个格式举行格式化:
https://i-blog.csdnimg.cn/direct/9018963f7ef3481dba8d49f72e9a946d.png
假如换成Timestamp:
https://i-blog.csdnimg.cn/direct/348b59f6410247dab209f5a7161eb51d.png
删除索引再新建查看:
https://i-blog.csdnimg.cn/direct/458b10e5ea534665aa07045ce251fe3d.png
可以看到是test类型的,后面会举行这个的测试,假如是这个类型会发生什么,下面是我之前遇到的一个bug:
关于easy-es对时间范围查询遇到的小bug-CSDN博客文章欣赏阅读195次。在利用easy-es之前作为一个小白的我只有es原生查询的基础,在自己通过查看官方文档自学easy-es遇到了一个妨害,其他的还好语法和MybatisPlus差不多,正以为我觉得很快就能入手,在对。https://g.csdnimg.cn/static/logo/favicon32.icohttps://blog.csdn.net/qq_73440769/article/details/144786181?spm=1001.2014.3001.5501保留为Timestamp加上一个注解再去测试:
@IndexField(fieldType = FieldType.DATE) https://i-blog.csdnimg.cn/direct/bfa0c726f63640e29245ac80a02ba278.png
https://i-blog.csdnimg.cn/direct/6c4f056f63254401878232a7a11467d6.png
可以看到可以格式化了,也是一个时间的格式,后面的演示我们利用LocalDateTime这个类型
2.批量新增文档数据

// 插入一条记录,默认插入至当前mapper对应的索引
Integer insert(T entity);
// 插入一条记录 可指定具体插入的路由
Integer insert(String routing, T entity);
// 父子类型 插入一条记录 可指定路由, 父id
Integer insert(String routing, String parentId, T entity);
// 插入数据 可指定具体插入的索引,多个用逗号隔开
Integer insert(T entity, String... indexNames);
// 插入数据,可指定路由及多索引插入
Integer insert(String routing, T entity, String... indexNames);
// 父子类型 插入数据,可指定路由,父id及多索引插入
Integer insert(String routing, String parentId, T entity, String... indexNames);

// 批量插入多条记录
Integer insertBatch(Collection<T> entityList)
// 批量插入 可指定路由
Integer insertBatch(String routing, Collection<T> entityList);
// 父子类型 批量插入 可指定路由, 父id
Integer insertBatch(String routing, String parentId, Collection<T> entityList);

// 批量插入多条记录 可指定具体插入的索引,多个用逗号隔开
Integer insertBatch(Collection<T> entityList, String... indexNames);
// 批量插入 可指定路由及多索引
Integer insertBatch(String routing, Collection<T> entityList, String... indexNames);
// 父子类型 批量插入 可指定路由,父id及多索引
Integer insertBatch(String routing, String parentId, Collection<T> entityList, String... indexNames);
参数说明:
类型参数名形貌Stringrouting路由StringindexNames索引列表Tentity实体对象Collection<T>entityList实体对象聚集
https://i-blog.csdnimg.cn/direct/a93ff8b5a3a84dd5895a9597caff2245.png
    /**
    * <p>
    * description: 批量新增文档
    * </p>
    *
    * @param count 前端入参:需要插入文档数量
    * @return: java.lang.Integer
    * @author: bluefoxyu
    * @date: 2024-12-28 16:38:26
    */
    @PostMapping("/insertBatch")
    public Integer insertBatch(@RequestParam Integer count) {
      return insertDocuments(count);
    }

    /**
   * 批量插入 1000 条数据到 Elasticsearch
   */
    public int insertDocuments(int count) {
      List<Document> documents = generateDocuments(count);
      documentMapper.insertBatch(documents);
      System.out.println("成功插入 1000 条数据到 Elasticsearch");
      return count;
    }

    /**
   * 生成指定数量的 Document 数据
   *
   * @param count 数据数量
   * @return 数据列表
   */
    public List<Document> generateDocuments(int count) {
      List<Document> documents = new ArrayList<>();
      Random random = new Random();

      // 当前时间为基准
      LocalDateTime baseTime = LocalDateTime.now();

      for (int i = 1; i <= count; i++) {
            // 创建时间在基准时间基础上随机增加若干秒
            LocalDateTime createTime = baseTime.plusSeconds(random.nextInt(86400)); // 随机一天内的秒数

            Document document = Document.builder()
                  .id(i) // 模拟自增 ID
                  .title("Document Title " + i)
                  .content("This is the content of document " + i)
                  .createTime(createTime)
                  .build();

            documents.add(document);
      }

      return documents;
    } https://i-blog.csdnimg.cn/direct/e905029ba8ae44cdbff144786c459913.png
https://i-blog.csdnimg.cn/direct/fbdf6702d43943a7a677092c1c1b1319.png
kibana中测试:
https://i-blog.csdnimg.cn/direct/b03fbc0a4bc947fb9b307e45d1311db4.png
https://i-blog.csdnimg.cn/direct/c2307d3fd5dd475e847eba5daa1ba534.png
3.批量删除

这里的删除和MybatisPlus一致,这里演示全部删除
    /**
    * <p>
    * description: 全部删除
    * </p>
    *
    * @return: java.lang.Integer
    * @author: bluefoxyu
    * @date: 2024-12-28 16:53:13
    */
    @DeleteMapping("/deleteAll")
    public Integer deleteAll() {
      // 创建删除条件:match_all 表示匹配所有文档
      LambdaEsQueryWrapper<Document> deleteWrapper = new LambdaEsQueryWrapper<>();
      deleteWrapper.matchAllQuery(); // 匹配所有文档
      return documentMapper.delete(deleteWrapper);
    } https://i-blog.csdnimg.cn/direct/ba1b971b318b47ba82c89561dde850d6.png
https://i-blog.csdnimg.cn/direct/9194ab8c14a84e04993065b6e7be075f.png
// 根据 ID 删除
Integer deleteById(Serializable id);
// 根据 ID 删除 可指定路由
Integer deleteById(String routing, Serializable id);
// 根据 ID 删除 可指定具体的索引,多个用逗号隔开
Integer deleteById(Serializable id, String... indexNames);
// 根据 ID 删除 可指定路由及多索引
Integer deleteById(String routing, Serializable id, String... indexNames);

// 根据 entity 条件,删除记录
Integer delete(LambdaEsQueryWrapper<T> wrapper);

// 删除(根据ID 批量删除)
Integer deleteBatchIds(Collection<? extends Serializable> idList);
// 删除(根据ID 批量删除)可指定路由
Integer deleteBatchIds(String routing, Collection<? extends Serializable> idList);
// 删除(根据ID 批量删除)可指定具体的索引,多个用逗号隔开
Integer deleteBatchIds(Collection<? extends Serializable> idList, String... indexNames);
// 删除(根据ID 批量删除) 可指定路由及多索引
Integer deleteBatchIds(String routing, Collection<? extends Serializable> idList, String... indexNames);
参数说明:
类型参数名形貌Stringrouting路由StringindexNames索引列表Wrapper<T>queryWrapper实体包装类 QueryWrapperSerializableid主键IDCollection<? extends Serializable>idList主键ID列表 4.修改

//根据 ID 更新
Integer updateById(T entity);
// 根据 ID 更新 可指定路由
Integer updateById(String routing, T entity);
// 根据 ID 更新 可指定具体的索引,多个用逗号隔开
Integer updateById(T entity, String... indexNames);
// 根据 ID 更新 可指定路由和多索引
Integer updateById(String routing, T entity, String... indexNames);


// 根据ID 批量更新
Integer updateBatchByIds(Collection<T> entityList);
// 根据ID 批量更新 可指定路由
Integer updateBatchByIds(String routing, Collection<T> entityList);

//根据 ID 批量更新 可指定具体的索引,多个用逗号隔开
Integer updateBatchByIds(Collection<T> entityList, String... indexNames);
// 根据ID 批量更新 可指定路由及多索引
Integer updateBatchByIds(String routing, Collection<T> entityList, String... indexNames);

// 根据动态条件 更新记录
Integer update(T entity, LambdaEsUpdateWrapper<T> updateWrapper);
参数说明
类型参数名形貌Stringrouting路由StringindexNames索引列表Tentity实体对象Wrapper<T>updateWrapper实体对象封装操纵类 UpdateWrapperCollection<T>entityList实体对象聚集 不过这里我比较喜欢利用链式的写法:
    /**
    * <p>
    * description: 根据id修改文档内容
    * </p>
    *
    * @param id 文档id
    * @param title 文档title
    * @param content 文档content
    * @return: java.lang.Integer
    * @author: bluefoxyu
    * @date: 2024-12-28 17:18:56
    */
    @PutMapping("/updateById/{id}")
    public Integer updateById(@PathVariable Integer id,@RequestParam String title,@RequestParam String content) {
      return EsWrappers.lambdaChainUpdate(documentMapper)
                .eq(Document::getId, id)
                .set(Document::getTitle, title)
                .set(Document::getContent, content)
                .update();
    } https://i-blog.csdnimg.cn/direct/380cc591f754468ea50b4732291dfdd8.png
https://i-blog.csdnimg.cn/direct/0a50ca57dfbd4dee8402352d502e2ced.png
5.查询

        // 获取总数
    Long selectCount(LambdaEsQueryWrapper<T> wrapper);
    // 获取总数 distinct为是否去重 若为ture则必须在wrapper中指定去重字段
    Long selectCount(Wrapper<T> wrapper, boolean distinct);
   
        // 根据 ID 查询
    T selectById(Serializable id);
    // 根据 ID 查询 可指定路由
    T selectById(String routing, Serializable id);

    // 根据 ID 查询 可指定具体的索引,多个用逗号隔开
    T selectById(Serializable id, String... indexNames);
    // 根据 ID 查询 可指定路由及多索引
    T selectById(String routing, Serializable id, String... indexNames);

    // 查询(根据ID 批量查询)
    List<T> selectBatchIds(Collection<? extends Serializable> idList);
    // 查询(根据ID 批量查询) 可指定路由
    List<T> selectBatchIds(String routing, Collection<? extends Serializable> idList);

    // 查询(根据ID 批量查询)可指定具体的索引,多个用逗号隔开
    List<T> selectBatchIds(Collection<? extends Serializable> idList, String... indexNames);
    // 查询(根据ID 批量查询) 可指定路由及多索引
    List<T> selectBatchIds(String routing, Collection<? extends Serializable> idList, String... indexNames);

    // 根据动态查询条件,查询一条记录 若存在多条记录 会报错
    T selectOne(LambdaEsQueryWrapper<T> wrapper);
    // 根据动态查询条件,查询全部记录
    List<T> selectList(LambdaEsQueryWrapper<T> wrapper);
参数说明:
类型参数名形貌Stringrouting路由StringindexNames索引列表Wrapper<T>queryWrapper实体包装类 QueryWrapperSerializableid主键IDCollection<? extends Serializable>idList主键ID列表 普通写法:

    /**
    * <p>
    * description: 根据title模糊查询(普通写法)
    * </p>
    *
    * @return: java.util.List<com.bluefoxyu.easyes.sample.domain.Document>
    * @author: bluefoxyu
    * @date: 2024-12-28 17:36:58
    */
    @GetMapping("/searchByTitle1")
    public List<Document> searchByTitle1() {
      // 3.查询出所有标题为老汉的文档列表
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.like(Document::getTitle, "修改");
      return documentMapper.selectList(wrapper);
    } https://i-blog.csdnimg.cn/direct/6cf83121e3b74546bc585f41efd06a1c.png
链式写法:

    /**
   * <p>
   * description: 根据title模糊查询(链式写法)
   * </p>
   *
   * @return: java.util.List<com.bluefoxyu.easyes.sample.domain.Document>
   * @author: bluefoxyu
   * @date: 2024-12-28 17:36:58
   */
    @GetMapping("/searchByTitle2")
    public List<Document> searchByTitle2() {
      // 3.查询出所有标题为老汉的文档列表
      return EsWrappers.lambdaChainQuery(documentMapper)
                .like(Document::getTitle, "修改")
                .list();
    } https://i-blog.csdnimg.cn/direct/5b4fcdc22f9d422cabc083ad42cc76a9.png
时间范围查询:

    /**
   * <p>
   * description: 根据 createTime 查询文档列表(链式写法)
   * </p>
   *
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @return: java.util.List<com.bluefoxyu.easyes.sample.domain.Document>
   * @author: bluefoxyu
   * @date: 2024-12-28 17:40:58
   */
    @GetMapping("/searchByCreateTime")
    public List<Document> searchByCreateTime(@RequestParam LocalDateTime startTime, @RequestParam LocalDateTime endTime) {

      // 需要进行格式匹配
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

      // 查询出 createTime 在 startTime 和 endTime 之间的文档列表
      return EsWrappers.lambdaChainQuery(documentMapper)
                .ge(Document::getCreateTime, startTime.format(formatter)) // 大于或等于开始时间
                .le(Document::getCreateTime, endTime.format(formatter))   // 小于或等于结束时间
                .list();
    } 需要举行格式化:
https://i-blog.csdnimg.cn/direct/58198b8a1bdd420b8e5b4114218d9bd7.png
https://i-blog.csdnimg.cn/direct/1587bdcf19234b00a38fb493f0363010.png

八、四大嵌套查询

这里主要内容都是参考官方文档,可以移步官方文档举行学习:
四大嵌套查询 | Easy-Es傻瓜级ElasticSearch搜刮引擎ORM框架https://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.easy-es.cn/pages/17ea0a/
ES四大嵌套查询

MySQLMybatis-PlusESEasy-Esand 嵌套and(Consumer)mustand(Consumer)or 嵌套or (Consumer)shouldor (Consumer)无无filterfilter(Consumer)无无must_notnot(Consumer) ES四大拼接查询

MySQLMybatis-PlusESEasy-Esand 拼接默认must默认or 拼接or()shouldor()无无filterfilter()无无must_notnot() 官方文档案例

下面是官方文档的一些案例,在现实的开发中都经常利用:
    /**
   * 场景一: 嵌套and的使用
   */
    @Test
    public void testNestedAnd() {
      // 下面查询条件等价于MySQL中的 select * from document where star_num in (1, 2) and (title = '老汉' or title = '推*')
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.in(Document::getStarNum, 1, 2)
               .and(w -> w.eq(Document::getTitle, "老汉").or().eq(Document::getTitle, "推*"));
      List<Document> documents = documentMapper.selectList(wrapper);
    }

    /**
   * 场景二: 拼接and的使用
   */
    @Test
    public void testAnd(){
      // 下面查询条件等价于MySQL中的 select * from document where title = '老汉' and content like '推*'
      // 拼接and比较特殊,因为使用场景最多,所以条件与条件之间默认就是拼接and,所以可以直接省略,这点和MP是一样的
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.eq(Document::getTitle, "老汉")
               .match(Document::getContent, "推*");
      List<Document> documents = documentMapper.selectList(wrapper);
    }
   
    /**
   * 场景二: 嵌套or的使用
   */
    @Test
    public void testNestedOr() {
      // 下面查询条件等价于MySQL中的 select * from document where star_num = 1 or (title = '老汉' and creator = '糟老头子')
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.eq(Document::getStarNum, 1)
                .or(i -> i.eq(Document::getTitle, "老汉").eq(Document::getCreator, "糟老头子"));
      List<Document> documents = documentMapper.selectList(wrapper);
    }

    /**
   * 场景三: 拼接or的使用
   */
    @Test
    public void testOr() {
      // 下面查询条件等价于MySQL中的 select * from document where title = '老汉' or title = '痴汉'
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.eq(Document::getTitle, "老汉")
                .or()
                .eq(Document::getTitle, "痴汉");
      List<Document> documents = documentMapper.selectList(wrapper);
    }

    /**
   * 场景四: 嵌套filter的使用 其实和场景一一样,只不过filter中的条件不计算得分,无法按得分排序,查询性能稍高
   */
    @Test
    public void testNestedFilter() {
      // 下面查询条件等价于MySQL中的 select * from document where star_num in (1, 2) and (title = '老汉' or title = '推*')
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.in(Document::getStarNum, 1, 2)
                .filter(w -> w.eq(Document::getTitle, "老汉").or().eq(Document::getTitle, "推*"));
      List<Document> documents = documentMapper.selectList(wrapper);
    }
   
    /**
   * 场景五: 拼接filter的使用 filter中的条件不计算得分,无法按得分排序,查询性能稍高
   */
    @Test
    public void testFilter() {
      // 下面查询条件等价于MySQL中的 select * from document where title = '老汉'
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.filter().eq(Document::getTitle, "老汉");
      List<Document> documents = documentMapper.selectList(wrapper);
    }
   
    /**
   * 场景六: 嵌套mustNot的使用
   */
    @Test
    public void testNestedNot() {
      // 下面查询条件等价于MySQL中的 select * from document where title = '老汉' and (size != 18 and age != 18)
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.eq(Document::getTitle, "老汉")
               .not(i->i.eq(size,18).eq(age,18));
      List<Document> documents = documentMapper.selectList(wrapper);
    }
   
    /**
   * 场景六: 拼接not()的使用
   */
    @Test
    public void testNot() {
      // 下面查询条件等价于MySQL中的 select * from document where title = '老汉' andsize != 18
      LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
      wrapper.eq(Document::getTitle, "老汉")
               .not()
               .eq(size,18);
      List<Document> documents = documentMapper.selectList(wrapper);
    }
九、链式调用

参考官方文档:
链式调用 | Easy-Es傻瓜级ElasticSearch搜刮引擎ORM框架https://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.easy-es.cn/pages/e36140/一样平常链式调用有下面三种,这些也是我比较喜欢的一致方法,一样平常利用的比较多:
// 索引链式构造器
LambdaEsIndexChainWrapper<T> lambdaChainIndex(BaseEsMapper<T> baseEsMapper);
// 查询链式构造器
LambdaEsQueryChainWrapper<T> lambdaChainQuery(BaseEsMapper<T> baseEsMapper);
// 更新(含删除)链式构造器
LambdaEsUpdateChainWrapper<T> lambdaChainUpdate(BaseEsMapper<T> baseEsMapper);
官网案例:
// 索引链式构造器
LambdaEsIndexChainWrapper<T> lambdaChainIndex(BaseEsMapper<T> baseEsMapper);
// 查询链式构造器
LambdaEsQueryChainWrapper<T> lambdaChainQuery(BaseEsMapper<T> baseEsMapper);
// 更新(含删除)链式构造器
LambdaEsUpdateChainWrapper<T> lambdaChainUpdate(BaseEsMapper<T> baseEsMapper);
上面这些对于我们一样平常开发结合MybatisPlus的语法已经够用了,假如想更好的拓展可以移步官方文档举行学习:
混合查询 | Easy-Es傻瓜级ElasticSearch搜刮引擎ORM框架https://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.easy-es.cn/pages/5743eb/查询字段过滤 | Easy-Es傻瓜级ElasticSearch搜刮引擎ORM框架https://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.easy-es.cn/pages/bbee1a/
十、MySQL和EE语法对比

参考官方文档:
MySQL和EE语法对比 | Easy-Es傻瓜级ElasticSearch搜刮引擎ORM框架https://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.easy-es.cn/pages/8f3438/
MySQLEasy-Eses-DSL/es java apiandandboolQueryBuilder.must(queryBuilder) 盘算得分andfilterboolQueryBuilder.filter(queryBuilder)不盘算得分ororboolQueryBuilder.should(queryBuilder)!notboolQueryBuilder.mustNot(queryBuilder)=eqterm>gtQueryBuilders.rangeQuery('es field').gt()>=ge.rangeQuery('es field').gte()<lt.rangeQuery('es field').lt()<=le.rangeQuery('es field').lte()like '%field%'likeQueryBuilders.wildcardQuery(field,value)not like '%field%'notLikemust not wildcardQuery(field,value)like '%field'likeLeftQueryBuilders.wildcardQuery(field,*value)like 'field%'likeRightQueryBuilders.wildcardQuery(field,value*)betweenbetweenQueryBuilders.rangeQuery('es field').from(xx).to(xx)is nullisNullmust not QueryBuilders.existsQuery(field)ininQueryBuilders.termsQuery(" xx es field", xx)group bygroupByAggregationBuilders.terms()order byorderByfieldSortBuilder.order(ASC/DESC)minminAggregationBuilders.minmaxmaxAggregationBuilders.maxavgavgAggregationBuilders.avgsumsumAggregationBuilders.sumorder by xxx ascorderByAscfieldSortBuilder.order(SortOrder.ASC)order by xxx descorderByDescfieldSortBuilder.order(SortOrder.DESC)joinnestedQueryBuilders.nestedQuery()-matchmatchQuery-matchPhraseQueryBuilders.matchPhraseQuery-matchPrefixQueryBuilders.matchPhrasePrefixQuery-queryStringQueryQueryBuilders.queryStringQueryselect *matchAllQueryQueryBuilders.matchAllQuery()-highLightHighlightBuilder.Field......... 末了,本博客仅用为个人一样平常学习easy-es的学习条记,自己工作上利用的多的记一记,希望也可以给大家带来便捷的利用和学习。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: SpringBoot中easy-es入门实战(最完整-结合官方文档版)