Working with views

Working with views

Describes how to query the bucket using Views.

When you query a view, you need to supply three params:

  • The name of the design document
  • The name of the view
  • Optional query options.

All of that is done through a DSL which you pass in to the query() method. The following example shows how to query a view on the beer-sample bucket and sets some options:

Observable<ViewResult> result = bucket.query(
    ViewQuery
        .from("beer", "brewery_beers")
        .descending()
        .limit(10)
);

The ViewResult contains the following properties:

  • rows : A potentially empty Observable with all the rows returned.
  • totalRows : The total number of rows in that view.
  • success : If the query was successful.
  • error : contains the error msg if the query was not successful.
  • debug : contains debug information if debug() was supplied.

The following code queries the view, prints out the found document IDs if succeeded or the error message if failed:

bucket
    .query(ViewQuery.from("beer", "brewery_beers"))
    .doOnNext(new Action1<ViewResult>() {
        @Override
        public void call(ViewResult viewResult) {
            if (!viewResult.success()) {
                System.err.println(viewResult.error());
            }
        }
    })
    .flatMap(new Func1<ViewResult, Observable<ViewRow>>() {
        @Override
        public Observable<ViewRow> call(ViewResult viewResult) {
            return viewResult.rows();
        }
    })
    .subscribe(new Action1<ViewRow>() {
        @Override
        public void call(ViewRow row) {
            System.out.println(row.id());
        }
    });

Every ViewRow also has a document() method, which allows you to load the full document content if needed. If you are only interested in the document referenced by the row, you can use flatMap() to get directly to it:

bucket
    .query(ViewQuery.from("beer", "brewery_beers"))
    .doOnNext(viewResult -> {
        if (!viewResult.success()) {
            System.err.println(viewResult.error());
        }
    })
    .flatMap(ViewResult::rows)
    .flatMap(ViewRow::document)
    .subscribe(System.out::println);