Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying couchbase by passing some value dynamically

I am having couchbase documents stored in below format:

{
"userEmail": "[email protected]",
"hashedPassword": "$2a$12$MT31FHNEbOAKpQGzLdBB3uhLlPlGNU0cvsgi/2pt4TdwPjvrUzkSG",
"type": "user",
}

I want to read only the document which is having userEmail value as [email protected]. For this I wrote a couchbase view:

function (doc, meta) {
  if(doc.userEmail == "[email protected]")
      emit(doc.data, meta.id);
}

Now what I want is, I want to pass value "[email protected]" 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.

like image 641
Yo Yo Saty Singh Avatar asked Dec 26 '22 01:12

Yo Yo Saty Singh


1 Answers

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:

  • if you have both json and non-json documents in your bucket you can map only json documents by checking meta.type == "json".
  • the resulting index will always have the document's ID, there's no need to emit it (or the whole document) as it grows the index size unnecessarily.

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".

like image 197
Simon Baslé Avatar answered Feb 15 '23 17:02

Simon Baslé