How to write query to my Cloudant database?

1.4k views Asked by At

I am trying to achieve the right query for my NoSQL database, but I am confused how to do it in Cloudant. In SQL with be

SELECT * FROM mydb
WHERE user_permit_doc_id = 10 
AND user_tracking_id = 1

My query is like:

https://293e2cb7-3561-4004-a1c3-58d54f517ee6-bluemix.cloudant.com/user_files/_design/user_tracking/_view/new-view?startkey=["user_permit_doc_id:10"]

and it returns all of the docs, not just the ones with this id.

this is m Map Reduce function for the View

function(doc) {
    if(doc.user_tracking_id !== null){
        emit(doc);
    }
}

Example of a doc inside my database of docs

{
  "_id": "6e57baa78c6415beeee788bc786cc53a",
  "_rev": "5-f15352bce99c307bd246bda4dc0da75a",
  "user_tracking_id": "1",
  "user_permit_id": "2",
  "user_permit_doc_id": "10",
  "user_id": "1",
  "_attachments": {
    "6y41j4i68cic.jpg": {
      "content_type": "image/jpeg",
      "revpos": 2,
      "digest": "md5-KC+G5tbz2UWZSzlPHvBy/Q==",
      "length": 68367,
      "stub": true
    }
  }
}
2

There are 2 answers

0
dbrugger On BEST ANSWER

you can change your view into

function(doc) {
  if(doc.user_tracking_id !== null){
    emit([user_tracking_id, user_permit_doc_id]);
  }
}

and then query using the complex key [1, 10]

3
Jake Peyser On

You would have to incorporate the WHERE user_permit_doc_id = 10 into your map reduce function if you wanted to return only that particular document, like this:

function(doc) {
   if(doc.user_permit_doc_id === 10 && doc.user_tracking_id === 1){
      emit(doc);
   }
}

However, since you are coming over from SQL, you might be more comfortable with Mongo-like queries. If that style of querying your DB suits you better, check out the Cloudant Mango API layer. This API introduces SQL-like querying to NoSQL, actually creating a map reduce function behind the scenes.