Search code examples
nosqlcouchdbcouchdb-mango

Build couchbdb view to index all documents whose ID starts with various three or four characters?


I'm new to nosql and views. Wondering if someone could show me how to build an index such that it will return all the different documents that apply multiple different keys. An example is below.

I have many many documents that all have the naming convention as follows:

AABA_August-11-2017_2017-06-29_10
BBY_August-11-2017_2017-06-29_10
CECO_January-19-2018_2017-06-08_19
GEL_December-15-2017_2017-06-08_1
Etc..

I'd like a view such that I could query on "starts with BBY" for example. And it would return all the documents that start with BBY. Maybe even "BBY_December", "BBY_August" etc.

Wondering if this is possible and what it would look like. I'm using CouchDB which uses Mango to build indexes. If someone could just point me in the right direction that would help too.

Thanks


Solution

  • You could write such a view like this:

    function(doc) {
        var docId = doc._id;
        var p = docId.substring(0, 2); // Or however many chars you want
        if (p === 'BBY') emit(doc._id, doc); // Or whatever kind of key you want
    }
    

    And then write similar views for alternate prefixes. You can also use query parameters similar to the _all_docs endpoint with views (http://docs.couchdb.org/en/2.0.0/api/ddoc/views.html).

    I think the only benefit of using a view instead of what you have done is that you can filter unnecessary fields, do some basic transformations, etc.

    Considering the similarities between retrieval from _all_docs vs from a view, it looks like the _all_docs endpoint is just index similar to a custom view. But I'm not sure on that.

    Not sure how to use Mango to do the same.