开发者

How do I design a couchdb view for following case ?

开发者 https://www.devze.com 2023-04-12 15:56 出处:网络
I am migrating an application from mySQL to couchDB. (Okay, Please dont pass judgements on this). There is a function with signature

I am migrating an application from mySQL to couchDB. (Okay, Please dont pass judgements on this).

There is a function with signature

getUserBy($开发者_如何学JAVAcolumn, $value) 

Now you can see that in case of SQL it is a trivial job to construct a query and fire it.

However as far as couchDB is concerned I am supposed to write views with map functions

Currently I have many views such as

get_user_by_name
get_user_by_email 

and so on. Can anyone suggest a better and yet scalable way of doing this ?


Sure! One of my favorite views, for its power, is by_field. It's a pretty simple map function.

function(doc) {
    // by_field: map function
    // A single view for every field in every document!
    var field, key;

    for (field in doc) {
        key = [field, doc[field]];
        emit(key, 1);
    }
}

Suppose your documents have a .name field for their name, and .email for their email address.

To get users by name (ex. "Alice" and "Bob"):

GET /db/_design/example/_view/by_field?include_docs=true&key=["name","Alice"]
GET /db/_design/example/_view/by_field?include_docs=true&key=["name","Bob"]

To get users by email, from the same view:

GET /db/_design/example/_view/by_field?include_docs=true&key=["email","alice@gmail.com"]
GET /db/_design/example/_view/by_field?include_docs=true&key=["name","bob@gmail.com"]

The reason I like to emit 1 is so you can write reduce functions later to use sum() to easily add up the documents that match your query.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号