REST API for Create a View with reduce function


#1

As doc of CBL’s REST API shows, we can create a view by REST API.

PUT /beer-db/_design/beer4 HTTP/1.1
Host: localhost:59840
{
    "language" : "javascript",
    "views" : {
        "brewery_beers" : {
            "map" : "function(doc) {if (doc.brewery_id) {emit(doc.brewery_id)}}"
        }
    }
}

I want to know Can I create a view with reduce function by REST API?
If yes,Can any one give me a View Create sample and a Query sample?


#2

Yes. The CouchDB documentation is probably the best description of how to do this.


#3

OK,Thanks, I will try.


#4

Hi, I just Create a view by REST API as follows:

PUT /beer-db/_design/beer4 HTTP/1.1
Host: localhost:59840
{
    "language" : "javascript",
    "views" : {
        "brewery_beers" : {
            "map" : "function(doc) {if (doc.brewery_id) {emit(doc.brewery_id)}}",
            "reduce" : "function(keys, values, rereduce) {return sum(values)}"
        }
    }
}

but it doesn’t work.
I am not sure the body is right or not?


#5

Well, you didn’t emit any values from your map function, so each row’s value will be null. I don’t think the sum function likes nulls; it expects numbers. Try emit(doc.brewery_id, 1).


#6

@Jens, it seems that @atom_yang followed the Couchbase documentation. Does your suggestion mean that {emit(doc.brewery_id)} is incorrect?


#7

The example in the documentation didn’t have a reduce function; it’s correct as an example of mapping. But when you’re reducing, the data being reduced is the values, so emitting a null value isn’t generally useful.


#8

Here is a example, hope can help other people.