本次实验使用的是
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基本一致,可以参照下文来满足自身的查询需求。
创建service
分页查询
public Page<OperationLogModel> getAll(Pageable pageable) {
Page<OperationLogModel> iterable = operationLogRepository.findAll(pageable);
return iterable;
}
上述代码即可实现分页查询功能,但要记住因为elasticsearch默认查询结果最大为10000,所以要避免pagesize>10000.
当我测试了 pagesize>10000时就会报以下错误
如果你的业务需求就是要获取大于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版本已经移除了。(所以这算不算是官方文档有误之处?),参照我上文的写法就好了。