Skip to content
This repository was archived by the owner on Mar 9, 2022. It is now read-only.

TouchDB Ektorp Views

mschoch edited this page May 25, 2012 · 8 revisions

It may not be obvious at first how you can use TouchDB Views (implemented in Java) with the standard Ektorp API. Below is small example of how it can be done.

  1. First set up your TDServer as described in the page Getting Started

  2. Next, define a view with design document name and view name you want.

    String dDocName = "ddoc";
    String viewName = "people";
    TDView view = db.getViewNamed(String.format("%s/%s", dDocName, viewName));
  1. Next, add the map/reduce implementation blocks for this view.
    view.setMapReduceBlocks(new TDViewMapBlock() {

        @Override
        public void map(Map<String, Object> document, TDViewMapEmitBlock emitter) {
            String type = (String)document.get("type");
            if("person".equals(type)) {
                emitter.emit(null, document.get("_id"));
            }
        }
    }, null, "1.0");
  1. Now you can query this view using the normal Ektorp API:
    ViewQuery viewQuery = new ViewQuery().designDocId(dDocName).viewName(viewName);
    ViewResult viewResult = couchDbConnector.queryView(viewQuery);
  1. If you follow these steps, custom CouchDbDocument subclasses and the repository support classes should also work.

CouchDbRepositorySupport Example

Here are some steps to use the CouchDbRepositorySupport class described by David K Pham:

  1. Properly describe my model so Ektorp knows how to map rows to it. Further explanation can be found here http://www.ektorp.org/reference_documentation.html#d100e313
  2. Setup an all view for the model in the database early on in the application lifecycle before you try to retrieve all the documents for that model:
TDView allView = db.getViewNamed("EmailAccount/all");
		
allView.setMapReduceBlocks(new TDViewMapBlock() {
        @Override
	public void map(Map<String, Object> document, TDViewMapEmitBlock emitter) {
		String type = document.get("type");

                if (type.equals("email_account") == true) {
                        emitter.emit(null, document.get("_id"));	
		}
         }
}, null, "1.0");
  1. Create a CouchDbRepositorySupport class:
public class EmailAccountRepository extends CouchDbRepositorySupport<EmailAccount> {
        public EmailAccountRepository(CouchDbConnector couchDBConnector) {
                super(EmailAccount.class, couchDBConnector);
        }
}
  1. Now you can retrieve all the documents for that model:
EmailAccountRepository emailAccountRepository = new EmailAccountRepository(CouchDBManager.getCouchDBConnector());

List<EmailAccount> emailAccounts = emailAccountRepository.getAll();

@Views annotation

Currently this is not supported.

Clone this wiki locally