Search code examples
mapreducecouchbasecouchbase-view

Couchbase view using “WHERE” clause dynamically


I have Json Documents in the following format

Name :
Class :
City :
Type :
Age :
Level :
Mother :
Father :

I have a map function like this

function(doc,meta)
{
    emit([doc.Name,doc.Age,doc.Type,doc.Level],null);
}

What I can do is give "name" and filter out all results but what I also want to do is give "age" only and filter out on that. For that couchbase does not provide functionality to skip "Name" key. So I have to create a new map function which has "Age" as first key, but I also have to query on only "Level" key also so like this. I would have to create many map functions for each field which obviously is not feasible so is there anything I can do apart from making new map function to achieve this type of functionality? I can't us n1ql because I have 150 million documents so it will take a lot of time.


Solution

  • First of all - that is not a very good reduce function.

    1. it does not have any filtering
    2. function header should be function(doc, meta)
    3. if you have mixture between json and binary objects - add meta.type == "json"

    Now for the things you can do:

    1. If you are using v4 and above (v4.1 in much more recommended) you can use N1QL and use it very similar to SQL language. (I didn't understand why you can't use n1ql)
    2. You can emit multiple items in multiple order

    i.e. if I have doc in the format of

    {
      "name": "Roi",
      "age": 31
    }
    

    I can emit to the index two values:

    function (doc, meta) {
      if (meta.type=="json") {
        emit(doc.name, null);  
        emit(doc.age, null);
      }
    }
    

    Now I can query by 2 values. this is much better than creating 2 views.

    Anyway, if you have something to filter by - it is always recommended.