How to Pagination of Results on Large size of data by using CBLQuery

Hi
I want Pagination of Results, like my total objects are 100, i want pagination like 100-80, 80-60… 20-0

For this i had used CBLQuery as like below code.

let query = CBLQueryBuilder(database: Constants.appDeleRef.database, select: nil, wherePredicate: predicate, orderBy: orderlist, error: nil)
let queryObj : CBLQuery = query.createQueryWithContext(nil)
queryObj.descending = true
queryObj.startKey = 10
queryObj.limit = 10
let result : CBLQueryEnumerator = try! queryObj.run()

But i’m getting 0 result from above query. Does anything wrong with Query.

I think you are looking for the skip property, not the startKey property. startKey and endKey are for use with the keys you emitted in your map function. The skip property is used for ignoring the first X number of entries in the query.

@borrrden Thanks for reply, so i have to do like this below.

Can you please elaborate more on startKey and endKey

let query = CBLQueryBuilder(database: Constants.appDeleRef.database, select: nil, wherePredicate: predicate, orderBy: orderlist, error: nil)
let queryObj : CBLQuery = query.createQueryWithContext(nil)
queryObj.descending = true
queryObj.skip = totalrecords - 10
queryObj.limit = 10
let result : CBLQueryEnumerator = try! queryObj.run()

One way to paginate by n items is to start with skip=0 and limit = n, then keep adding n to skip until you get zero results.

It doesn’t scale well, though, because when you use skip, the query still has to go through the work of finding those results and skipping them.

A better way is to take the key of the last row you got, and use it as the startKey of the next query. (Also set inclusiveStart=false so you don’t repeat that key.) This works unless you have duplicate keys; then it gets a little trickier. Let me know if that’s the case.

FYI, documentation on startKey/endKey (and all the other query stuff) is here.

Thank you @jens i will check it.

@jens Thanks for your glad help on this, I’m doing Doc id as unique. because Im not giving Doc Id. so its taking automatically default ID.

As of my requirement, i want to show the recently created rows (i keep createdDate in the doc file) top and then rest of things, in this scenario. what is startKey value.

View keys aren’t the same as document IDs. And since you’re using the query builder, it’s defining the keys for you, so you don’t need to worry about them much.

As I said, “take the key of the last row you got, and use it as the startKey of the next query”. For this purpose it doesn’t matter what the keys are. All that matters to you is that the query is returning the rows in order by key.

@Jens, Thank you i got solution as like you said with Skip and Limit properties.