springboot整合elasticsearch7.3.0

本次实验使用的是
springboot 2.3.11
ElasticSearch 7.3.0
(springboot 2.1.x的版本对应"spring-boot-starter-data-elasticsearch"版本不兼容elasticSearch7.3.0)

引入依赖

spring-boot-starter-data-elasticsearch

增加配置文件

spring:
  elasticsearch:
    rest:
      # 逗号分隔的Elasticsearch实例使用的列表
      uris: http://ip:port

创建model类

package com.example.demo.elasticsearch.model;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;



@Data
@Document(indexName = "operationlog")
public class OperationLogModel {
    @Id
    String id;

    String idens;

    String operationLog;

    Long timestamp;
}

创建Repository

public interface OperationLogRepository extends ElasticsearchRepository<OperationLogModel,String> {

}

与JPA基本一致,可以参照下文来满足自身的查询需求。

image.png

image.png

image.png

创建service

分页查询

public Page<OperationLogModel> getAll(Pageable pageable) {
    Page<OperationLogModel> iterable = operationLogRepository.findAll(pageable);


    return iterable;
}

上述代码即可实现分页查询功能,但要记住因为elasticsearch默认查询结果最大为10000,所以要避免pagesize>10000.
当我测试了 page
size>10000时就会报以下错误

image.png

如果你的业务需求就是要获取大于10000条记录的话,可以使用scroll来获取。

scroll获取所有的记录

@Autowired
private ElasticsearchRestTemplate esTemplate;

public void scroll(String name){
    IndexCoordinates index = IndexCoordinates.of("operation");
    FieldSortBuilder fsb = SortBuilders.fieldSort("timestamp").order(SortOrder.DESC);
    Query searchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.matchQuery("name",name))
            .withSort(fsb)
            .withPageable(PageRequest.of(0, 10))
            .build();
    SearchScrollHits<OperationLogModel> scroll = esTemplate.searchScrollStart(1000, searchQuery, OperationLogModel.class, index);

    String scrollId = scroll.getScrollId();
    List<SearchHit<OperationLogModel>> sampleEntities = new ArrayList<>();
    while (scroll.hasSearchHits()) {
        sampleEntities.addAll(scroll.getSearchHits());
        scrollId = scroll.getScrollId();
        scroll = esTemplate.searchScrollContinue(scrollId, 1000, OperationLogModel.class,index);
    }
    System.out.println(sampleEntities.size());
}

下图是在官网上给的scroll的例子,例子中的SearchQuery在spring-boot-starter-data-elasticsearch4.0.9版本已经移除了。(所以这算不算是官方文档有误之处?),参照我上文的写法就好了。

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值