Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a single value from document

Tags:

couchdb

Is there a possibility in CouchDB to retrieve a single value from a document? For example, I have a document with 10000 keys like this:

{
   "_id": "8098091cc795acde43cd45335373cc92",
   "_rev": "2-6d2e0ac43618388cc958b91e5015bba5",
   "1":"some value",
   "2":"another value",
   ...
   "10000":"last value"
}

and I don't want to parse the whole document each time but just want to get a value of key "2". Is this possible?

EDIT:

Of course, before asking this question I looked through the docs and googled around this but haven't found such possibility. But I'm wondering why this is not possible? In my understanding it is not too much difference between view and document since both of them are sets of key-value pairs, but it is possible to get single value from view using ?key=... in the query string and not possible to do the same for document. Why?

like image 592
Vader Avatar asked Sep 13 '11 21:09

Vader


2 Answers

You can use a CouchDB show function to process a document on the server and send arbitrary data to the client. Show functions can do simple things like extracting a single value from the document; or they can convert to a completely different content-type such as XML.

For example:

  • In database db
  • which has design document _design/example with show function one_field
  • you want to fetch document with ID doc_id
  • but only retrieve the field some_field which has a value "I am the some_field value!"

That query would be:

GET /db/_design/example/_show/one_field/doc_id?name=some_field

The show function would look like this:

function(doc, req) {
  // _show function to extract one field

  var field_name = req.query.name; // Set to e.g. "some_field"
  var field_value = doc[field_name];

  return { "code": 200   // HTTP status code
         , "headers":    // Response headers
           { "content-type": "text/plain" }
         , body: field_value
         };
}

The design document would look like this:

{ "_id": "_design/example"
, "shows":
  { "one_field": ... } // Paste the above function as a string.
}

CouchDB will return

HTTP 200 OK
Content-Type: text/plain
Content-Length: 26

I am the some_field value!
like image 129
JasonSmith Avatar answered Oct 15 '22 16:10

JasonSmith


No. CouchDB is a document oriented DB, so it doesn't support more granular access to the data beyond the overall document itself.

It gives you fine grained indexing, but not actual access.

like image 25
Will Hartung Avatar answered Oct 15 '22 17:10

Will Hartung