Couchdb example: list as key

From wikinotes
Revision as of 00:46, 9 December 2016 by Will (talk | contribs) (Created page with "Couchdb allows you to use arbitrary datastructures as keys. In order to make this useful for query parameters, you'll likely want to '''iterate over your key's values''', and...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Couchdb allows you to use arbitrary datastructures as keys. In order to make this useful for query parameters, you'll likely want to iterate over your key's values, and match against one of the values.

In this example we'll use tags attached to a tasklist as an excuse.


create documents

{
"_id": "go to grocery store",
"tags" ["daytime"]
}

{
"_id": "think up xmas gifts",
"tags": ["fun","daytime","nighttime"],
}

{
"_id": "stargaze",
"tags": ["fun","nighttime"]
}

creating view

Instead of yielding the entire list of tags, we are yielding every tag in every document.

# testdb/_design/testdg/_view/bytag
function( doc ){
	for (var i in doc.tags){
		emit( doc.tags[i], doc.id );
	}
}

querying

Query all documents with the tag "nighttime".

curl -X GET localhost:5984/testdb/_design/testdsg/_view/bytag?key="nighttime"
{"total_rows":2,"offset":0,"rows":[
{"id":"think up xmas gifts", "key":"nighttime",  "value":null},
{"id":"stargaze",            "key":"nighttime",  "value":null},
]}