Question

CouchDB docs seem to have a key attached; it does not show up when retrieving a single document but you can use them to retrieve ranges of documents such as :

 wget "http://localhost:5984/monitor20n/_all_docs?startkey=1111&endkey=2222

However, apparently that key is always the same as the document id, so that all you obtain is stuff like this

{"total_rows":14269,"offset":0,"rows":[
{"id":"128127896626798592","key":"128127896626798592","value":{"rev":"1-4e07e2c4b4eddfad5846ddf905337197"}},
{"id":"128128575021907970","key":"128128575021907970","value":{"rev":"1-43d983af1e837a4415b6167cae3b5de8"}},
... and so on }}

(see here key == id ). However, you can use more complex keys in views, including vectors which allow for much more complex interaction; at least, you can set the keys of views so you can now in advance what to search without looking up document ids. The question is now: Can you set those keys up when creating a document? Or maybe after creating it? An obvious workaround is to create a view like this

function (doc) {
    emit(doc.key,doc)
}

however, I would like to know if there's a more direct way of obtaining the same effect.

Was it helpful?

Solution

Keys are an important part of CouchDB views. With a view, the key does not have to be the document ID. But the only way to produce a key is to use the emit function from within a view. There is no property that you can set that will automatically become the key.

Think of _all_docs like a built in view. To be consistent it follows the same output as a regular view, and it uses the id as the key. But you can't change the _all_docs view. If you wanted to provide your own _id when you save a document, that will end up being the key. So if you wanted custom 'keys' in the '_all_docs' view you could create docs like this:

{ _id: 'Sample1' }, {_id: 'My2'}. and after they are saved, when you request the '_all_docs' view you would get: {"total_rows":2,"offset":0,"rows":[ {"id":"Sample1","key":"Sample1","value":{"rev":"1-4e07e2c4b4eddfad5846ddf905337197"}}, {"id":"My2","key":"My2","value":{"rev":"1-43d983af1e837a4415b6167cae3b5de8"}}, ... and so on }}

Here is a link about what makes a documentID:

http://wiki.apache.org/couchdb/HTTP_Document_API#Special_Fields

While it does not say explicitly, you can't use objects or arrays as DocumentIDs.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top