Spring data elastisearch如何使用偏移和限制来查询。我想使用偏移和限制参数来查询页面。但是我找不到方法支持。例如:
queryBuild.withPageable(PageRequest.of(pageIndex, pageSize));
Page<Content> content = elasticsearchOperations.queryForPage(queryBuild.build(),Content.class);
它可能是好的
但是我找不到偏移和限制的方法
queryBuild.withPageable(PageRequest.of(offset, limit));
我也有同样的问题,所以我实现了以下类
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public class OffsetLimitPageable implements Pageable {
private int offset;
private int page;
private int size;
private Sort sort = Sort.unsorted();
protected OffsetLimitPageable(int offset, int page, int size) {
if (offset < 0) {
throw new IllegalArgumentException("Offset must not be less than zero!");
}
if (page < 0) {
throw new IllegalArgumentException("Page index must not be less than zero!");
}
if (size < 1) {
throw new IllegalArgumentException("Page size must not be less than one!");
}
this.offset = offset;
this.page = page;
this.size = size;
}
public static OffsetLimitPageable of(int offset, int page, int size) {
return new OffsetLimitPageable(offset, page, size);
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#getPageNumber()
*/
@Override
public int getPageNumber() {
return page;
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#getPageSize()
*/
@Override
public int getPageSize() {
return size;
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#getOffset()
*/
@Override
public long getOffset() {
return offset + page * size;
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#getSort()
*/
@Override
public Sort getSort() {
return sort;
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#next()
*/
public Pageable next() {
return of(offset, page + 1, size);
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#previousOrFirst()
*/
public Pageable previousOrFirst() {
return hasPrevious() ? of(offset, page - 1, size) : first();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#first()
*/
public Pageable first() {
return of(offset, 0, size);
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Pageable#hasPrevious()
*/
public boolean hasPrevious() {
return page > 0;
}
}
像这样使用
queryBuild.withPageable(OffsetLimitPageable.of(offset, page, limit));
spring-data-es(或任何spring-data项目)不支持这一点,因此您必须为Pagable
接口提供自己的自定义实现
如果您尝试使用存储库变体(扩展Elasticsearch chRepository
然后执行查询,就像您注意到的那样,使用
PageRequest p = new MyOwnPageRequest(offset, limit);
SearchQuery sq = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withPageable(p)
.build();
Page<SampleEntity> result = elasticsearchTemplate.queryForPage(sq, SampleEntity.class);