Springboot2.x整合ElasticSearch

Springboot2.x整合ElasticSearch

1.学习的本位的条件:必须安装es:elasticsearch和kibana的Linux安装
Windows的安装大家自己搜索吧
2.maven配置:详细的请看下面的源码

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

yml配置

server:
  port: 9099

#开发配置
spring:
  datasource:
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/es_db?serverTimezone=GMT%2B8
    username: root
    password: ls123
    ## Elasticsearch配置文件(必须)
    ## 该配置和Elasticsearch的elasticsearch.yml中的配置信息有关
  data:
    elasticsearch:
      cluster-name: my-application
      cluster-nodes: 192.168.221.132:9300
mybatis-plus:
  map-underscore-to-camel-case: true
  mapper-locations: classpath:mappers/*.xml
  type-aliases-package: com.ls.pojo
  configuration:      #配置打印mysql日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    com.ls.dao.es: debug

ItemRepository不要加注解

public interface ItemRepository extends ElasticsearchRepository<Item,Long > {
}

test类

@RunWith(SpringRunner.class)
@SpringBootTest
@MapperScan("com.ls.dao")
public class EsDemoTest01 {


  @Autowired
  private ElasticsearchTemplate elasticsearchTemplate;

  @Autowired
  private ItemRepository itemRepository;
  @Autowired
  private ItemMapper itemMapper;
  
}

es的JavaAPI学习

@Data
@Accessors(chain = true)
@ApiModel(value = "Item对象", description = "商品表")
@TableName("tb_item")
@Document(indexName = "item", type = "docs", shards = 1, replicas = 0)
public class Item{

  public Item(String itemName, String sellPoint, Long price, Integer num, String brand,
      String image, Long cid) {
    this.itemName = itemName;
    this.sellPoint = sellPoint;
    this.price = price;
    this.num = num;
    this.brand = brand;
    this.image = image;
    this.cid = cid;
  }

  public Item() {
  }

  private static final long serialVersionUID = 1L;
  @ApiModelProperty("id")
  @TableId(type = IdType.AUTO)
  private Long id;
  @ApiModelProperty(value = "商品名称")
  private String itemName;

  @ApiModelProperty(value = "商品卖点")
  private String sellPoint;

  @ApiModelProperty(value = "商品价格,单位为:分")
  private Long price;

  @ApiModelProperty(value = "库存数量")
  private Integer num;

  @ApiModelProperty(value = "商品条形码")
  private String brand;

  @ApiModelProperty(value = "商品图片")
  private String image;

  @ApiModelProperty(value = "所属类目,叶子类目")
  private Long cid;

  @ApiModelProperty(value = "商品状态,1-正常,2-下架,3-删除")
  private Integer status;

  @ApiModelProperty(value = "创建时间")
  private Date createTime;

  @ApiModelProperty(value = "更新时间")
  private Date modifyTime;
}

1.存入向es单条数据

/**
   * 存入单条
   */
  @Test
  public void testSave() {
    Item item = new Item("奔驰s400", "双排气", 666666666l, 5, "奔驰",
        "https://www.mercedes-benz.com.cn/?smtid=570962679z32cmz2dt02z1pdz0z", 5L);
    int rows = itemMapper.insert(item);
    Long id = item.getId();
    Item dnItem = itemMapper.selectById(id);
    if (rows < 1) {
      throw new RuntimeException();
    }
    //api
    itemRepository.save(dnItem);
  }

kibana查看所有的

GET _search
{
  "query": {
    "match_all": {}
  }
}

Springboot2.x整合ElasticSearch_第1张图片
2.存入多条

 /**
   * 保存多条
   */
  @Test
  public void testSaveAll() {
    List<Long> ids = new ArrayList<>();
    ids.add(1L);
    ids.add(2L);
    ids.add(3L);
    List<Item> items = itemMapper.selectBatchIds(ids);
    for (Item item : items) {
      System.out.println(item);
    }
    itemRepository.saveAll(items);
  }

3.创建索引和删除

 /**
   * 创建索引,会根据Item类的@Document注解信息来创建
   */
  @Test
  public void testCreateIndex() {
    elasticsearchTemplate.createIndex(Item.class);
  }

  /**
   * 删除索引
   */
  @Test
  public void testDeleteIndex() {
    elasticsearchTemplate.deleteIndex(Item.class);
  }
  /**
   * 删除所有的()
   */
  @Test
  public void testDeleteAll() {
    itemRepository.deleteAll();
  }

4.查找所有的

 /**
   * 查找所有的
   */
  @Test
  public void testFindAll() {
    Iterable<Item> all = itemRepository.findAll();

    for (Item item : all) {
      System.out.println(item);
    }
  }

5.配置映射

 /**
   * 配置映射,会根据Item类中的id、Field等字段来自动完成映射
   */
  @Test
  public void testPutMapping() {
    elasticsearchTemplate.putMapping(Item.class);
  }

6.查询按价格排序从高到低

/**
   * 查询按价格排序从高到低
   */
  @Test
  public void testSort() {
    Iterable<Item> all = itemRepository.findAll(Sort.by("price").descending());

    for (Item item : all) {
      System.out.println(item);
    }
  }

7.自定义查询,在ItemRepository添加方法

 /**
   * 根据商品标题查询:如
   * @param itemName
   * @return
   */
  List<Item> findByItemName(String itemName );

  /**
   * 区间查找
   * @param
   * @param
   * @return
   */
  List<Item> findByPriceBetween(Long minPrice, Long maxPrice);

测试

 /**
   * 自定义方法查询,方法名要遵循命名规则,方法名要符合一定的约定
   */
  @Test
  public void testFindByTitle() {
    List<Item> item = itemRepository.findByItemName("三");

    for (Item item1 : item) {

      System.out.println(item1);
    }
  }

  /**
   * 价格区间查询
   */
  @Test
  public void testFindByPriceBetween() {
  List<Item> item = itemRepository.findByPriceBetween(3000L, 6000L);
    for (Item item1 : item) {

      System.out.println(item1);
    }
  }

8.matchQuery的使用

 /**
   * matchQuery底层采用的是词条匹配查询
   */
  @Test
  public void testMatchQuery() {

    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    queryBuilder.withQuery(QueryBuilders.matchQuery("itemName", "奔驰"));
    Page<Item> page = itemRepository.search(queryBuilder.build());
    long totalElements = page.getTotalElements();
    System.out.println("共有:" + totalElements);
    for (Item item : page) {
      System.out.println(item);
    }


  }

9.termQuery的查询

/**
   * 词条匹配查询
   */
  @Test
  public void testTermQuery() {
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

    queryBuilder.withQuery(QueryBuilders.termQuery("price", 3000));

    Page<Item> page = itemRepository.search(queryBuilder.build());

    for (Item item : page) {
      System.out.println(item);
    }
  }

10.BooleanQuery的查询

 @Test
  public void testBooleanQuery() {
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    queryBuilder.withQuery(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("itemName", "华为"))
        .must(QueryBuilders.matchQuery("num", 100)));
    Page<Item> page = itemRepository.search(queryBuilder.build());

    for (Item item : page) {
      System.out.println(item);
    }
  }

11.模糊查询FuzzyQuery


  /**
   * 模糊查询,最多错2次
   */
  @Test
  public void testFuzzyQuery() {
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    queryBuilder.withQuery(QueryBuilders.fuzzyQuery("itemName", "华"));

    Page<Item> page = itemRepository.search(queryBuilder.build());

    for (Item item : page) {
      System.out.println(item);
    }

  }

12.分页查询

@Test
  public void testPage() {

    int pageNum = 0;
    int pageSize = 11;

    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

    queryBuilder.withQuery(QueryBuilders.matchQuery("cid", 3));

    queryBuilder.withPageable(PageRequest.of(pageNum, pageSize));

    Page<Item> page = itemRepository.search(queryBuilder.build());

    for (Item item : page) {
      System.out.println(item);
    }

  }

聚合查询

 /**
   * 以品牌分组,求组内情况
   */
 @Test
  public void testAgg() {
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 不查询任何结果
    queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
    // 1、添加一个新的聚合,聚合类型为terms,聚合名称为brands,聚合字段为brand
    queryBuilder.addAggregation(
        AggregationBuilders.terms("brands").field("brand.keyword"));
    // 2、查询,需要把结果强转为AggregatedPage类型
    AggregatedPage<Item> aggPage = (AggregatedPage<Item>) this.itemRepository
        .search(queryBuilder.build());
    // 3、解析
    // 3.1、从结果中取出名为brands的那个聚合,
    // 因为是利用String类型字段来进行的term聚合,所以结果要强转为StringTerm类型
    StringTerms agg = (StringTerms) aggPage.getAggregation("brands");
    // 3.2、获取桶
    List<StringTerms.Bucket> buckets = agg.getBuckets();
    // 3.3、遍历
    for (StringTerms.Bucket bucket : buckets) {
      // 3.4、获取桶中的key,即品牌名称
      System.out.println(bucket.getKeyAsString());
      // 3.5、获取桶中的文档数量
      System.out.println(bucket.getDocCount());
    }

  }
/**
   * 分组和平均值计算
   */
  @Test
  public void testSubAgg() {
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 不查询任何结果
    queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
    // 1、添加一个新的聚合,聚合类型为terms,聚合名称为brands,聚合字段为brand
    queryBuilder.addAggregation(
        AggregationBuilders.terms("brands").field("brand.keyword")
            .subAggregation(AggregationBuilders.avg("priceAvg").field("price"))
        // 在品牌聚合桶内进行嵌套聚合,求平均值
    );
    // 2、查询,需要把结果强转为AggregatedPage类型
    AggregatedPage<Item> aggPage = (AggregatedPage<Item>) this.itemRepository
        .search(queryBuilder.build());
    // 3、解析
    // 3.1、从结果中取出名为brands的那个聚合,
    // 因为是利用String类型字段来进行的term聚合,所以结果要强转为StringTerm类型
    StringTerms agg = (StringTerms) aggPage.getAggregation("brands");
    // 3.2、获取桶
    List<StringTerms.Bucket> buckets = agg.getBuckets();
    // 3.3、遍历
    for (StringTerms.Bucket bucket : buckets) {
      // 3.4、获取桶中的key,即品牌名称  3.5、获取桶中的文档数量
      System.out.println(bucket.getKeyAsString() + ",共" + bucket.getDocCount() + "台");

      // 3.6.获取子聚合结果:
      InternalAvg avg = (InternalAvg) bucket.getAggregations().asMap().get("priceAvg");
      System.out.println("平均售价:" + avg.getValue());
    }

  }

GitHub的源码和SQL:https://github.com/smileLs66/es
可参考:https://www.cnblogs.com/leeSmall/p/9218779.html
更多的学习请访问官网文档

你可能感兴趣的:(中间件,es)