9

I would like to query for a list of particular documents with one call to CouchDB.

With SQL I would do something like

SELECT *
FROM database.table
WHERE database.table.id
IN (2,4,56);

What is a recipe for doing this in CouchDB by either _id or another field?

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
johowie
  • 2,475
  • 6
  • 26
  • 42

2 Answers2

7

You need to use views keys query parameter to get records with keys in specified set.

function(doc){
    emit(doc.table.id, null);
}

And then

GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]

To retrieve document content in same time just add include_docs=True query parameter to your request.

UPD: Probably, you might be interested to retrieve documents by this reference ids (2,4,56). By default CouchDB views "maps" emitted keys with documents they belongs to. To tweak this behaviour you could use linked documents trick:

function(doc){
    emit(doc.table.id, {'_id': doc.table.id});
}

And now request

GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]&include_docs=True

will return rows with id field that points to document that holds 2,4 and 56 keys and doc one that contains referenced document content.

Kxepal
  • 4,659
  • 1
  • 19
  • 16
  • 1
    using the `keys` parameter in the url clarifies things for me greatly. I just had an Aha! moment. thanks (ps. spelling mistake on 'linked documents' link) – johowie Oct 06 '12 at 20:42
3

In CouchDB Bulk document APi is used for this:

curl -d '{"keys":["2","4", "56"]}' -X POST http://127.0.0.1:5984/foo/_all_docs?include_docs=true

http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API

Anthony
  • 12,407
  • 12
  • 64
  • 88
  • Also, do you know if the Bulk document API has any significant performance difference to a writing a `view` that emits `emit(doc._id, doc)` OR `emit(doc._id, doc._id)` with `?include_docs=true` – johowie Oct 10 '12 at 21:31
  • Yes, that works for IDs, that's correct. As far as I know _all_docs is also a view so there should be no difference in performance. – Anthony Oct 11 '12 at 15:55