EelasticSearch使用

1. Easy-ES介绍

Easy-Es

傻瓜级ElasticSearch搜索引擎ORM框架

2. 导入依赖包

XML 复制代码
  <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>cn.easy-es</groupId>
            <artifactId>easy-es-boot-starter</artifactId>
            <version>2.0.0-beta1</version>
        </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>

3. 在对像属性上添加注解

注解 | Easy-Es

傻瓜级ElasticSearch搜索引擎ORM框架

java 复制代码
@IndexName( aliasName = "es_product")
public class EsProduct {

    @IndexId(type = IdType.CUSTOMIZE)
    private Integer id;
    @IndexField( fieldType= FieldType.TEXT, analyzer = Analyzer.IK_MAX_WORD,searchAnalyzer = Analyzer.IK_MAX_WORD)
    private String name;
    @IndexField( fieldType= FieldType.INTEGER)
    private Integer categoryId;
    @IndexField( fieldType= FieldType.DOUBLE) // 12.56
    private BigDecimal price;
    @IndexField( fieldType= FieldType.TEXT, analyzer = Analyzer.IK_MAX_WORD)
    private String brief;
    @IndexField( fieldType= FieldType.KEYWORD)
    private String img;
    @IndexField( fieldType= FieldType.TEXT, analyzer = Analyzer.IK_MAX_WORD)
    private List<String> tags;
    @IndexField( fieldType= FieldType.INTEGER) //198
    private Integer highOpinion;
    @IndexField( fieldType= FieldType.INTEGER)
    private Integer salesVolume;
    @IndexField( fieldType= FieldType.DATE)
    private LocalDateTime productionDate;
}

4.新建Mapper类,类似Mybatis的dao

java 复制代码
import cn.easyes.core.core.BaseEsMapper;



public interface ProductMapper  extends BaseEsMapper<Product> {

}

5.配置ES

java 复制代码
# Easy-Es配置部分
easy-es:
  # 启用Easy-Es功能
  enable: true
  # 设置Elasticsearch服务器地址和端口
  address: 192.168.21.100:9200
  # 全局配置项,设置是否打印执行的DSL语句(便于调试)
  global-config:
    print-dsl: true

6. 创建、删除、查询索引

分词&模糊匹配 | Easy-Es

傻瓜级ElasticSearch搜索引擎ORM框架

6.1 插入

java 复制代码
 @Test
    void insert1() {

        EsProduct esProduct = new EsProduct().setId(1)
                .setName("红米手机 苹果")
                .setSubTitle("小米(MI)Redmi K70 至尊版 天玑9300+ IP68 小米龙晶玻璃 12GB+256GB 晴雪白 小米红米K70 Ultra 5G手机")
                .setDescription("天玑 9300+\n" +
                        "MediaTek 迄今最强性能芯\n" +
                        "升级全大核 CPU 架构\n" +
                        "作为小米xMediaTek 联合实验室首款性能力作,RedmiK70 至尊版\n" +
                        "采用了 9300+旗舰芯片,主频高达3.4GHz,配备 Cortex-X4 大核\n" +
                        "架构。无论驾驭重载 3D游戏,还是重载应用,全然毫不费力。即\n" +
                        "便效果拉满,依旧狂暴持久。格力")
                .setPic("https://www.baidu.com")
                .setCategoryId(100)
                .setBrandName("小米")
                .setSaleCount(100)
                .setHighOpinion(105)
                .setPrice(new BigDecimal(1000))
                .setTags(CollUtil.newArrayList("小米", "手机","红米","老人机"));

        Integer rowNum = esProductDao.insert(esProduct);
    }
    @Test
    void insert2() {

        EsProduct esProduct = new EsProduct().setId(2)
                .setName("格力(GREE)KFR-35GW/NhGc1B")
                .setSubTitle("格力(GREE)空调 云佳【超级省电】新能效空调变频冷暖 自清洁 壁挂式空调挂机卧室变频空调冷暖空调冷暖 大1匹 一级能效 【适用10-15㎡】")
                .setDescription("4.50 旧国标一级能效\n" +
                        "APF:\n" +
                        "空调APF能效等级是空调评价指标\n" +
                        "APF数值越高越省电。苹果")
                .setPic("https://www.baidu.com")
                .setCategoryId(100)
                .setBrandName("格力")
                .setSaleCount(50)
                .setHighOpinion(205)
                .setPrice(new BigDecimal(2000))
                .setTags(CollUtil.newArrayList("格力", "夏天","避暑","节能","制冷","省电"));

        Integer rowNum = esProductDao.insert(esProduct);
    }
    @Test
    void insert3() {
         List productList = new ArrayList<EsProduct>();
        for (int i = 1; i <= 13; i++) {
            EsProduct esProduct = new EsProduct().setId(i)
                    .setName("Redmi K70")
                    .setSubTitle("小米(MI)Redmi K70 至尊版 天玑9300+ IP68 小米龙晶玻璃 12GB+256GB 晴雪白 小米红米K70 Ultra 5G手机")
                    .setDescription("天玑 9300+\n" +
                            "MediaTek 迄今最强性能芯\n" +
                            "升级全大核 CPU 架构\n" +
                            "作为小米xMediaTek 联合实验室首款性能力作,RedmiK70 至尊版\n" +
                            "采用了 9300+旗舰芯片,主频高达3.4GHz,配备 Cortex-X4 大核\n" +
                            "架构。无论驾驭重载 3D游戏,还是重载应用,全然毫不费力。即\n" +
                            "便效果拉满,依旧狂暴持久。")
                    .setPic("https://www.baidu.com")
                    .setBrandName("小米")
                    .setSaleCount(100)
                    .setCategoryId(100)
                    .setPrice(new BigDecimal(2599))
                    .setTags(CollUtil.newArrayList("小米", "手机","红米","老人机"))
                    .setProductionDate(LocalDate.now());
            productList.add(esProduct);
        }


        Integer rowNum = esProductDao.insertBatch(productList);
    }

6.2 删除

java 复制代码
    @Test
    void delete() {
        Integer integer = esProductDao.deleteBatchIds(CollUtil.newArrayList(1, 2, 3, 4, 5));
    }

6.3 更新

java 复制代码
 @Test
    void update() {
        EsProduct esProduct = new EsProduct().setId(1)
                .setName("红米手机 苹果15")
                .setSubTitle("小米(MI)Redmi K70 至尊版 天玑9300+ IP68 小米龙晶玻璃 12GB+256GB 晴雪白 小米红米K70 Ultra 5G手机")
                .setDescription("天玑 9300+\n" +
                        "MediaTek 迄今最强性能芯\n" +
                        "升级全大核 CPU 架构\n" +
                        "作为小米xMediaTek 联合实验室首款性能力作,RedmiK70 至尊版\n" +
                        "采用了 9300+旗舰芯片,主频高达3.4GHz,配备 Cortex-X4 大核\n" +
                        "架构。无论驾驭重载 3D游戏,还是重载应用,全然毫不费力。即\n" +
                        "便效果拉满,依旧狂暴持久。格力")
                .setPic("https://www.baidu.com")
                .setCategoryId(100)
                .setBrandName("小米")
                .setSaleCount(1008)
                .setPrice(new BigDecimal(1000))
                .setTags(CollUtil.newArrayList("小米", "手机","红米","老人机"));
        Integer rowNum = esProductDao.updateById(esProduct);
    }

    @Test
    //部分更改
    void update2() {
        EsProduct esProduct = new EsProduct().setId(1)

                .setSaleCount(1009);

        Integer rowNum = esProductDao.updateById(esProduct);
    }
    @Test
        //部分更改
    void update3() {
        LambdaEsUpdateWrapper<EsProduct> wrapper = new LambdaEsUpdateWrapper<>();
        wrapper.eq(EsProduct::getCategoryId, 100);
        EsProduct document = new EsProduct();
        document.setName("隔壁老王王");
        Integer rowNum = esProductDao.update(document,wrapper);
    }

6.4 查询

java 复制代码
 @Test
    void select() {
        delete();
        insert1();
        insert2();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.eq(EsProduct::getId, 2); //where id = 2
        List<EsProduct> esProducts = esProductDao.selectList(wrapper);

    }
    @Test
    void select100() {
        delete();
        insert1();
        insert2();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.eq(EsProduct::getCategoryId, 200); //where categoryId = 200
        List<EsProduct> esProducts = esProductDao.selectList(wrapper);

    }
    @Test
    void select101() {
        delete();
        insert1();
        insert2();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.in(EsProduct::getCategoryId, 100,200); //where categoryId in (100,200)
        List<EsProduct> esProducts = esProductDao.selectList(wrapper);

    }
    @Test
    //根据单个字段模糊查询
    void select2() {
        delete();
        insert1();
        insert2();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.match(EsProduct::getName, "格力"); //where name like '%格力%'
        List<EsProduct> esProducts = esProductDao.selectList(wrapper);

    }
    @Test
    //根据所有字段模糊查询
    void select3() {
        delete();
        insert1();
        insert2();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.queryStringQuery("苹果"); //where name like '%苹果%' or subTitle like '%苹果%' ....
        List<EsProduct> esProducts = esProductDao.selectList(wrapper);
    }

    @Test
        //根据所有字段模糊查询
    void select4() {
        delete();
        insert1();
        insert2();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.in(EsProduct::getCategoryId, 100); //where categoryId in (100) and (name like '%苹果%' or subTitle like '%苹果%' or description like '%苹果%')
        wrapper.and(
                 w->w.match(EsProduct::getName, "小日本极小米粒",2.0F)
                         .or().match(EsProduct::getSubTitle, "小日本极小米粒",1.0F)
                         .or().match(EsProduct::getDescription, "小日本极小米粒",5.5F)
                );
        List<EsProduct> esProducts = esProductDao.selectList(wrapper);
    }
    @Test
     //排序
    void select5() {
        delete();
        insert1();
        insert2();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.in(EsProduct::getCategoryId, 100); //where categoryId in (100) and (name like '%苹果%' or subTitle like '%苹果%' or description like '%苹果%')
        wrapper.orderByDesc(EsProduct::getSaleCount);
        List<EsProduct> esProducts = esProductDao.selectList(wrapper);
    }
    @Test
        //分页
    void select6() {
        delete();
        insert3();
        LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.in(EsProduct::getCategoryId, 100); //where categoryId in (100) and (name like '%苹果%' or subTitle like '%苹果%' or description like '%苹果%')
        wrapper.orderByDesc(EsProduct::getSaleCount);
        EsPageInfo<EsProduct> esProductEsPageInfo = esProductDao.pageQuery(wrapper, 3, 5);

    }

7.关键字高亮

8. 原生Api调用

8.1查看索引mapping关系

GET /es_product/_mapping

8.2查看某个文档,具体字段的分词

GET /product/_doc/2/_termvectors?fields=brief

post _analyze
{
    "analyzer": "ik_max_word",
    "text": "极小米粒"
}


post _analyze
{
    "analyzer": "ik_max_word",
    "text": "大学生自习室视频爆火鼻祖"
}


GET  /es_product/_mapping 



GET /es_product/_doc/1/_termvectors?fields=description



post /es_product/_search
{
  "query": {
    "term": {
      "name": "手机"
    }
  }
}

1.综合使用

# -------------------es-----------------------
easy-es.address =192.168.23.27:9200
easy-es.global-config.print-dsl=true
java 复制代码
   @IndexName(value = "product", aliasName = "es_product")
19 @Data
20 @Builder
21 @AllArgsConstructor
22 @NoArgsConstructor
23 public class EsProduct {
24     @IndexId(type = IdType.CUSTOMIZE)
25     private Integer id;
26     @IndexField(fieldType = FieldType.TEXT, analyzer = Analyzer.IK_SMART, searchAnalyzer = Analyzer.IK_MAX_WORD)
27     private String name;
28     //FieldType.KEYWORD代表本身就是一个关键字(不可再分的关键字) 不需要再分了
29     @IndexField(fieldType = FieldType.KEYWORD)
30     private String brand;   //格力 美的 美特斯邦威
31     @IndexField(fieldType = FieldType.TEXT, analyzer = Analyzer.IK_SMART, searchAnalyzer = Analyzer.IK_MAX_WORD)
32     private String subName;
33     @IndexField(fieldType = FieldType.INTEGER)
34     private Integer categoryId;
35     @IndexField(fieldType = FieldType.DOUBLE)
36     private BigDecimal price;
37     @IndexField(fieldType = FieldType.TEXT, analyzer = Analyzer.IK_SMART, searchAnalyzer = Analyzer.IK_MAX_WORD)
38     private String brief;
39     //    @IndexField(exist=false)
40     @IndexField(fieldType = FieldType.NONE)
41     private String img;
42     @IndexField(fieldType = FieldType.TEXT, analyzer = Analyzer.IK_SMART, searchAnalyzer = Analyzer.IK_MAX_WORD)
43     private List<String> tags;
44     @IndexField(fieldType = FieldType.LONG)
45     private Integer highOpinion;    //好评
46     @IndexField(fieldType = FieldType.LONG)
47     private Integer salesVolume;    //销量
48     //排序
49     @IndexField(fieldType = FieldType.DATE)
50     private LocalDateTime productionDate;
51 }

20  @Data
21  public class EsProductQuery {
22 
23      private Integer categoryId;
24      private String keyWord;
25      private String tags;
26      private Integer highOpinion;
27      private Integer salesVolume;
28      private LocalDateTime productionDate;
29      private Integer pageSize;
30      private Integer pageNum;
31 
32  }
java 复制代码
public interface EsProductMapper extends BaseEsMapper<EsProduct> {
}
public Map<String, Object> ESSelect(EsProductQuery query) {

         LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();

         if (query.getCategoryId() != null) {
             wrapper.eq(EsProduct::getCategoryId, query.getCategoryId());
         }
         if (query.getTags() != null) {
             String tags = query.getTags();
             wrapper.match(EsProduct::getTags, tags);
         }

         if (query.getKeyWord() != null) {
             String keyWord = query.getKeyWord();
             wrapper.and(w->w.match(EsProduct::getName,keyWord,5f).or().match(EsProduct::getSubName,keyWord,3f).or().match(EsProduct::getBrief, keyWord,1f));
         }


         if (query.getSalesVolume() != null) {
             wrapper.orderByDesc(EsProduct::getSalesVolume);
         }

         if (query.getHighOpinion() != null) {
             wrapper.orderByDesc(EsProduct::getHighOpinion);
         }

         EsPageInfo<EsProduct> esProductEsPageInfo = esProductMapper.pageQuery(wrapper, query.getPageNum(), query.getPageSize());
         long total = esProductEsPageInfo.getTotal();
         List<EsProduct> list = esProductEsPageInfo.getList();

         Map<String, Object> map = new HashMap<>();
         map.put("items", list);
         map.put("total", total);
         String source = esProductMapper.getSource(wrapper);
         System.out.println(source);
         return map;
     }
相关推荐
朝九晚五ฺ11 分钟前
【Linux探索学习】第十四弹——进程优先级:深入理解操作系统中的进程优先级
linux·运维·学习
Heaphaestus,RC41 分钟前
【Unity3D】获取 GameObject 的完整层级结构
unity·c#
baivfhpwxf20231 小时前
C# 5000 转16进制 字节(激光器串口通讯生成指定格式命令)
开发语言·c#
直裾1 小时前
Scala全文单词统计
开发语言·c#·scala
Kkooe1 小时前
GitLab|数据迁移
运维·服务器·git
久醉不在酒2 小时前
MySQL数据库运维及集群搭建
运维·数据库·mysql
ZwaterZ3 小时前
vue el-table表格点击某行触发事件&&操作栏点击和row-click冲突问题
前端·vue.js·elementui·c#·vue
虚拟网络工程师3 小时前
【网络系统管理】Centos7——配置主从mariadb服务器案例(下半部分)
运维·服务器·网络·数据库·mariadb
BLEACH-heiqiyihu3 小时前
RedHat7—Linux中kickstart自动安装脚本制作
linux·运维·服务器
MXsoft6185 小时前
华为服务器(iBMC)硬件监控指标解读
大数据·运维·数据库