views:

97

answers:

2

Is it possible to search by key value in Apache CouchDB? Given the sample data below (spaced for readability):

{
"_id":"a754a63dcc7f319b02f7ce6de522ca26",
"_rev":"1-5bd88e53fe0869b8ce274b49a2c1ddf5",
"name":"john smith",
"email":"[email protected]",
"username":"jsmith"
}

Could I query the database for the user jsmith or for the user having the email [email protected]? How would I go about this?

Thanks!

+2  A: 

http://sitr.us/2009/06/30/database-queries-the-couchdb-way.html

Tobias
That's perfect, thanks!
Nate
+2  A: 

Yes, that is certainly possible. You will create a couple of views, which are sorted lists ("index") of your data, one per key.

Tobias's link is useful. However the standard CouchDB documentation will cover this also:

For example, in your design document, you might want a users_by_email view, with keys based on the email field; then a users_by_name view keyed on the username field, etc. Experiment with the temporary views in Futon until you get your function working just right, and then store it in your design document permanently.

Good luck!

P.S. There is a way to combine all of these requirements into one view. Briefly, you could key on ["email", "[email protected]"] or ["name": "john smith"] however remember, CouchDB is relaxed: The simpler method above will work fine. When you become comfortable with views, you can explore this "collated" style.

jhs
fyi - keys should be short because keys get saved within every object. i always try to keep em really small like "email" would be "m" or "e" - "username" would be "u"...just an fyi - nobody has to do it but if you store a lot of data it helps saving some space.
Tobias