androidcouchbasecouchbase-litecouchbase-view

Couchbase Lite: reading document vs querying data


I'm switching an Android project to using Couchbase Lite, and I'm confused with ways for fetching the data from the database.

I have a document, which contains only one property:

Map<String, Object> properties = new HashMap<String, Object>();
properties.put("data_key", json);
Document document = database.getDocument("data_doc_id");
document.putProperties(properties);

The next my step is getting the stored data from the database. I found two ways:

  1. The first approach is reading the document

    Document doc = database.getDocument("data_doc_id");
    String json = (String) doc.getProperty("data_key");
    
  2. The second one is querying

    View view = database.getView("data_json");
    view.setMap(new Mapper() {
    
    @Override
    public void map(Map<String, Object> document, Emitter emitter) {
        if ("data_doc_id".equals(document.get("_id")) {
            String json = (String) doc.getProperty("data_key");
            emitter.emit("data_key", json);
        }
    }
    }, "1.0");
    QueryEnumerator queryEnumerator = view.createQuery().run();
    String dataJson = "";
    
    for (QueryRow queryRow : run) {
        if ("data_key".equals(queryRow.getKey()) {
            json = (String) queryRow.getValue();        
        }    
    }
    

Is it okay to use the first approach to get the stored JSON?

For what cases the second approach should be used? It has far more code than the first one, maybe it has something to do with caching or/and speed/performance? What are the pros and cons of this approach?


Solution

  • The first approach is retrieving the document directly. This is the fastest way to do it.

    With databases, though, often you want to retrieve documents based on some feature of the data. To do this you want the ability to create queries about the data. That's what the second approach is for.