Matt
Matt

Reputation: 1811

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

Upvotes: 5

Views: 2200

Answers (2)

Marcello Nuccio
Marcello Nuccio

Reputation: 3901

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.

Upvotes: 4

Dominic Barnes
Dominic Barnes

Reputation: 28429

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

Upvotes: 2

Related Questions