Using createAllDocumentsQuery with limit to get count of all documents without limit

7 views
Skip to first unread message

Brendan Duddridge

unread,
Feb 15, 2017, 10:38:24 PM2/15/17
to Couchbase Mobile
Hi,

I'm doing an all docs query without and with a limit. Basically I'm looping through all my documents one batch at a time, but I'd like to find out how many records there are in total that match the query first before I break it up into batches. You know, so I can have a proper progress indicator showing how far we've gone.

So I have this code so far:

NSError *queryError = nil;

CBLQuery *docsQuery = [self.databaseDocument.backgroundDatabase createAllDocumentsQuery];

docsQuery.allDocsMode = kCBLBySequence;

docsQuery.startKey = @(sequence.integerValue + 1);

// Get the count of records

docsQuery.mapOnly = NO;

CBLQueryRow *rowCountQueryRow = [[docsQuery run: &queryError] nextRow];

NSNumber *fullRecordCount = rowCountQueryRow.value;


NSLog(@"Full record count: %@", fullRecordCount);


// Now fetch all the documents


docsQuery.mapOnly = YES;


if (limit) {

   docsQuery.limit = limit;

}  


CBLQueryEnumerator *docsEnumerator = [docsQuery run: &queryError];


I know the rowCountQueryRow.value won't get me the count as I've got it above, but that's the point of this email.

How do I get the count first when mapOnly = NO? There's no reduce function on an all docs query as far as I know.

Thanks,

Brendan

Jens Alfke

unread,
Feb 16, 2017, 12:09:24 PM2/16/17
to mobile-c...@googlegroups.com
You can’t use reduce or group on an all-docs query*. I think you’d have to make a view that just emits the doc’s sequence as its key, then query that.
(Which to me seems like too much overhead just to provide a progress bar, but that’s your call!)

You could always make a rough estimate of the count by subtracting the starting sequence number from the database’s lastSequenceNumber. That will give you the correct number if no document was updated more than once; otherwise it’ll be an overestimate.

—Jens

* In CBL 2.0 you’ll be able to! Something like “count(*) where _sequence > $lastSequence”.
Reply all
Reply to author
Forward
0 new messages