Android: Stop querying view once condition is satisfied

Is there a way to stop quering view once the IF-condition is met?

private View getSingleMessageView(final long messageId) {
    View view = couchbaseWrapper.getDatabase().getView("SINGLE_MESSAGE");
    if (view.getMap() == null) {
        Mapper map = new Mapper() {
            @Override public void map(Map<String, Object> document, Emitter emitter) {
                // TODO: How to stop query once if-statement is satisfied?
                if ("type")) &&
                        document.get("user_id").equals(getCurrentUserId()) &&
                        String.valueOf(document.get("message_id")).equals(String.valueOf(messageId))) {
                    emitter.emit(document.get("message_id"), null);
        view.setMap(map, "1.0");
    return view;

I tried setting query.setLimit(1) but the query still goes one.

That’s not really how this works. The map function creates an index. The query happens against the index after it’s built. So you can stop iterating over query results, but stopping building an index doesn’t really make sense.

You might look at all doc queries as an alternative. Those (like the name implies) query against all documents instead of building an index. Then you could stop iterating on the query results once you get what you want. You can also look at the filters available to apply to a query to help you narrow down the results returned.

What Hod said. Also, you cannot use getCurrentUserId() in a map function because it refers to external state. A map function has to be a “pure function” that always returns the same output given the same input — so it cannot use anything other than the document parameter and constants.

I recommend (re)reading the documentation on map/reduce views and queries. It can be a bit tricky to get your head around at first.

FYI - This tutorial on views should elaborate on what Hod and Jens described.