couchbasecouchbase-view

Querying couchbase by passing some value dynamically


I am having couchbase documents stored in below format:

{
"userEmail": "satyam@xyz.com",
"hashedPassword": "$2a$12$MT31FHNEbOAKpQGzLdBB3uhLlPlGNU0cvsgi/2pt4TdwPjvrUzkSG",
"type": "user",
}

I want to read only the document which is having userEmail value as satyam@xyz.com. For this I wrote a couchbase view:

function (doc, meta) {
  if(doc.userEmail == "satyam@xyz.com")
      emit(doc.data, meta.id);
}

Now what I want is, I want to pass value "satyam@xyz.com" from the Java code. I tried it a lot but couldn't find a proper solution. Can anybody help me out from this dilemma.

Thanks in advance for any kind of suggestions.


Solution

  • I think in fact you want to map your JSON documents by userEmail, so your map function should be something like this:

    function(doc, meta) {
        //maybe check the type of the document here, see meta.type
        emit(doc.userEmail, null)
    }
    

    Two notes:

    Now you can query the view by passing startkey and endkey arguments, with a little trick:

    ?startkey="theEmail"&endkey="theEmail\uefff"
    

    Here \uefff is the first unicode char, which allows to simulate an exact key match since there no other combination of characters between "myEmail" and "myEmail\uefff".