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":"jsmith@example.com",
"username":"jsmith"
}
Could I query the database for the user jsmith or for the user having the email jsmith@example.com? How would I go about this?
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_emailview, with keys based on theemailfield; then ausers_by_nameview keyed on theusernamefield, 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", "jsmith@example.com"]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.