Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite key with CouchDB, finding multiple records

I know you can pass a key or a range to return records in CouchDB, but I want to do something like this. Find X records that are X values.

So for example, in regular SQL, lets say I wanted to return records with ids that are 5, 7, 29, 102. I would do something like this:

SELECT * FROM sometable WHERE id = 5 OR id = 7 or id = 29 or id = 102

Is it possible to do this in CouchDB, where I toss all the values I want to find in the key array, and then CouchDB searches for all of those records that could exist in the "key parameter"?

like image 746
Matt Avatar asked May 28 '11 22:05

Matt


2 Answers

You can do a POST as documented on CouchDB wiki. You pass the list of keys in the body of the request.

{"keys": ["key1", "key2", ...]}

The downside is that a POST request is not cached by the browser.

Alternatively, you can obtain the same response using a GET with the keys parameter. For example, you can query the view _all_docs with:

/DB/_all_docs?keys=["ID1","ID2"]&include_docs=true

which, properly URL encoded, becomes:

/DB/_all_docs?keys=%5B%22ID1%22,%22ID2%22%5D&include_docs=true

this should give better cacheability, but keep in mind that _all_docs changes at each doc update. Sometimes, you can workaround this by defining your own view with only the needed documents.

like image 184
Marcello Nuccio Avatar answered Oct 19 '22 17:10

Marcello Nuccio


With a straight view function, this will not be possible. However, you can use a _list function to accomplish the same result.

like image 2
Dominic Barnes Avatar answered Oct 19 '22 16:10

Dominic Barnes