问题
In my project there is a service that retrieves a list of documents. Till now the way to retrieve them is with pagination object this way we don't send back to frontend all the elements.
public Page<Document> findDocumentPage(Pageable pageable) {
return this.documentService.findAllByPage(pageable);
}
The problem is that I need the global index of a document from all pages. For example lets say I have a list of pages with results after query:
firstResult:{
page: 1,
document_list: [{doc:{ id: a, content: ''}},
{doc:{ id: b, content: ''}},
{doc:{ id: c, content: ''}}]
}
secondResult:{
page: 2,
document_list: [{doc:{ id: d, content: ''}},
{doc:{ id: e, content: ''}},
{doc:{ id: f, content: ''}}]
}
These results are independent from each other. Is there a way to tell that document with id 'e' is the 5th element in all pages results without having access to previous page's results. Also pages can have different sizes some may have 30 results other 20, it can be x.
I'm okay with storing a list in backend with number of elements of previous pages, and then calculating the index based on page number, index on current page, and size of previous pages. However this does not seem as a neat solution to me.
回答1:
If you have the Page representing one of the results, this can be easily calculated for all elements in that page like so (modulo off-by-one errors):
globalIndex = page.getPageable().getOffset() + localIndex
Where localIndex
is the index of the element in question in page.getContent()
.
来源:https://stackoverflow.com/questions/64659193/retrieve-global-index-of-element-with-pagination-jpa-postgresql