better explain couchbase lite map function rules and common mistakes

313 views Asked by At

I am new to couchbase and I am trying to implement couchbase lite in one of my Android applications. What i am struggling with in particular is the concept of views and the rules for the map function as stated in the docs.

In the database the app stores documents with various doc types. In one query i need to get the entire document by document type ("payments") and by value of an attribute of the document (doc["approved"] = true)

Hence I would create a view like so:

   com.couchbase.lite.View view = database.getView("payments");
    if (view.getMap() == null) {
        Mapper map = new Mapper() {
            @Override
            public void map(Map<String, Object> doc, Emitter emitter) {
                if (doc.get("type").equals("payments") && doc.get("approved") == true) {
                    emitter.emit(doc.get("name"), doc); 
                }
            }
        };
        view.setMap(map, "1");
    }

Note that the doc["approved"] value can be updated over time. In one of the rules about map functions in the docs it says:

It must be a "pure" function: ... That means any time it's called with the same input, it must produce exactly the same output.

Would the implementation of the map function as show above violate that rule? In the docs it further says :

In particular, avoid these common mistakes: ... Don't make any assumptions about when the map function is called. That's an implementation detail of the indexer. (For example, it's not called every time a document changes.).

Does that mean when the approved status of one of the documents is updated from false to true that the following query not nessesarily contains the updated document? If so what would I need to do to achieve this? I am quite uncertain about what rule that exacly means? Could anyone try to open my eyes please?

1

There are 1 answers

0
borrrden On BEST ANSWER

What "pure" means is that you cannot use outside state in your map function. All your determinations must be based solely on the parameters that were passed into it. Your map function does not violate this.

I think the missing piece in your understanding is the difference between storage and indexing. You can store revisions of a document to the database, right? That in and of itself will not cause the view's index to be updated. That's what the documentation means by "not called every time a document changes." The index will be updated by default when the next query is run, so the newest state of the document will be output. It could realistically have been changed many times since the last query was run.