Creating a view through C API with Map and Reduce Functions


#1

Hello,

I am now creating views with the map functions using the C API.
However, I would like to know how do I also include a reduce Function too/

This is how i do the creation of views

    const string docid = "_design/" +_designName;

    string doc = "views":{
                            "myView":{
                             "map": "function (doc, meta) { SOME CODE; }"
                             } 
                        };

    
	lcb_http_cmd_t cmd;
	cmd.version = 0;
	cmd.v.v0.path = docid.c_str();
	cmd.v.v0.npath = docid.length();
	cmd.v.v0.body = doc.c_str();
	cmd.v.v0.nbody = doc.length();
	cmd.v.v0.method = LCB_HTTP_METHOD_PUT;
	cmd.v.v0.content_type = "application/json";
	lcb_error_t rc = lcb_make_http_request(m_Instance, NULL, LCB_HTTP_TYPE_VIEW, &cmd, NULL);

This works for me. But I dun know how I can add a reduce function too.
Please advise. :smile:

Thanks!


#2

Simply add a "reduce":"function(key,values,rereduce){...}" in the myView JSON dictionary


#3

const string docid = “_design/” +_designName;

string doc = "views":{
                        "myView":{
                         "map": "function (doc, meta) { SOME CODE; }"
                         "reduce": "function (key,values,rereduce) {REDUCE CODE;}"
                         } 
                    };


lcb_http_cmd_t cmd;
cmd.version = 0;
cmd.v.v0.path = docid.c_str();
cmd.v.v0.npath = docid.length();
cmd.v.v0.body = doc.c_str();
cmd.v.v0.nbody = doc.length();
cmd.v.v0.method = LCB_HTTP_METHOD_PUT;
cmd.v.v0.content_type = "application/json";
lcb_error_t rc = lcb_make_http_request(m_Instance, NULL, LCB_HTTP_TYPE_VIEW, &cmd, NULL);


if (rc != LCB_SUCCESS)
{
	cout << "Failed to Create views for Design: " << _designName <<  ". Error:  " << rc << endl;
}

I changed it to the above. But I still don’t see the reduce function in my couchbase console…

I believe there’s probably an error happening but I don’t seem to be able to catch it. I have added a LCB_SUCCESS line to know if it failed. but its not throwing any errors.


#4

LCB_SUCCESS will be returned if the actual I/O operation completed successfully. You would still need to inspect the actual HTTP status code (and body) to determine what went wrong at the HTTP level. Please note that you also need to invoke lcb_wait() for any network I/O to actually take place.