Skip to content

Instantly share code, notes, and snippets.

@lqd
Created March 6, 2012 15:02
Show Gist options
  • Save lqd/1986698 to your computer and use it in GitHub Desktop.
Save lqd/1986698 to your computer and use it in GitHub Desktop.
Lombok-free paginated view iterator for jcouchdb (cf https://gist.github.com/1986550)
import java.util.Iterator;
import java.util.List;
import org.jcouchdb.db.Database;
import org.jcouchdb.db.Options;
import org.jcouchdb.document.Document;
import org.jcouchdb.document.ValueRow;
import org.jcouchdb.document.ViewResult;
// Fast view pagination method described at http://guide.couchdb.org/draft/recipes.html#fast
public class PaginatedViewIterator<T extends Document> implements Iterator<List<ValueRow<T>>>
{
private Database database;
private String view;
private Class<T> documentClass;
private int rowsPerPage;
private Object nextStartKey;
private String nextStartKeyDocId;
private boolean hasNext = true;
public PaginatedViewIterator (Database database, String view, Class<T> documentClass, int rowsPerPage)
{
this.database = database;
this.view = view;
this.documentClass = documentClass;
this.rowsPerPage = rowsPerPage;
}
public boolean hasNext ()
{
return hasNext;
}
public List<ValueRow<T>> next()
{
Options options = new Options().limit (rowsPerPage + 1);
if (nextStartKey != null && nextStartKeyDocId != null)
options.startKey (nextStartKey)
.startKeyDocId (nextStartKeyDocId);
ViewResult<T> result = database.queryView (view, documentClass, options, null);
List<ValueRow<T>> allRows = result.getRows ();
int count = allRows.size ();
if (count <= rowsPerPage)
{
hasNext = false;
return allRows;
}
List<ValueRow<T>> rows = allRows.subList (0, rowsPerPage);
ValueRow<T> lastRow = allRows.get (count - 1);
nextStartKey = lastRow.getKey ();
nextStartKeyDocId = lastRow.getId ();
return rows;
}
@Override
public void remove ()
{
throw new IllegalStateException ("not supported");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment