incubator-couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Brian Candler <B.Cand...@pobox.com>
Subject Re: parametrized view generation
Date Wed, 10 Feb 2010 09:45:49 GMT
On Wed, Feb 10, 2010 at 11:14:30AM +0530, madhav sharma wrote:
> I am couchdb for one of my project and i am stuck at a place where i need
> your help.
> My use case of problem is that i have a set of documents which have same
> field with different value and i need to get the value of  field (say name)
> from a document with id (say information) , and i want this mapfunction to
> be generic so that i can call this with different document id and get the
> the field value out of it.
> In sql it can just be(  select name from Table where id = 1233 )  so any
> help is appreciated

In that particular case, you could just GET the document (since you use the
doc._id to GET a document)

select * from docs where id = 123
  => GET /dbname/123

select * from docs where id in (123,456)
  => POST /dbname/_all_docs?include_docs=true
     {"keys":["123","456"]}

If you're searching a field other than doc._id, then you make a map
function.

function(doc) {
  if (doc.name) {
    emit(doc.name, null);
  }
}

select * from docs where name = 'foo'
  => GET /dbname/_design/mydesign/_view/view1?key="foo"&include_docs=true

If you leave out include_docs=true then you will get the doc id, the emitted
key and the emitted value (here null), but not the rest of the doc.

If you always want to retrieve some other values from the doc, you can
include it in the value part, which is more efficient than fetching the
whole doc.  For example

function(doc) {
  if (doc.name) {
    emit(doc.name, doc.description || null);
  }
}

select description from docs where name = 'foo'
  => GET /dbname/_design/mydesign/_view/view2?key="foo"

But you can be cleverer, and do things which are much harder in SQL.  For
example, you can index all fields by value:

function(doc) {
  for (var k in doc) {
    emit(doc[k], k);
  }
}

select id from docs where name='foo' or description='foo' or label='foo' or...
  => GET /dbname/_design/mydesign/_view/view3?key="foo"

The result row will give you the match as the key, and the field it came
from as the value.

Or you can have a single index which lets you search on any specific field.

function(doc) {
  for (var k in doc) {
    emit([k, doc[k]], null);
  }
}

select id from docs where description='foo'
  => GET /dbname/_design/mydesign/_view/view4?key=["description","foo"]

Using startkey/endkey you can do searching for ranges and prefixes.

Hope this gives you a starting point.

Brian.

Mime
View raw message