Hi,
I'm trying to employ reduce to generate a tag cloud.
I have few documents in my db having a 'tags' field which contains a
list of strings.
My view functions looks like:
{
"every": "function(doc) {
if (doc.type == 'story')
{
for (i = 0; i < doc.tags.length; i++)
{
map(doc.tags[i], 0);
}
}
}",
"counts": {
"map": "function(doc)
{
if (doc.type == 'story')
{
for (i = 0; i < doc.tags.length; i++) {
map(doc.tags[i], doc.tags[i]);
}
}
}",
"reduce": "function(doc, values)
{
var result = {};
for (i = 0; i < values.length; i++)
{
if (typeof(values[i]) == 'string')
{
if (result[values[i]] == undefined)
{
result[values[i]] = 1;
} else
{
result[values[i]] = result[values[i]] + 1;
}
} else /* merge with previous reduce result */
{
for (v in values[i])
{
if (result[v] == undefined) {
result[v] = 1;
} else
{
result[v] = result[v] + values[i][v]
}
}
}
}
; return result;
}"
}
}
(in short, i'm trying to emulate group reduce there, having a js
associative array as a reduce result, which maps tag name -> counter )
'every' view works ok, just to illustrate: it returns every tag for my db:
{"total_rows":10,"offset":0,"rows":[
{"id":"d5fff2a7b520c87180502a05847dfbd5","key":"ar","value":0},
{"id":"95e7802ec6e00e803b780ad46cc473c4","key":"arg","value":0},
{"id":"3d3a04e08b0c67f295f6acd9ff422e13","key":"argh","value":0},
{"id":"3d3a04e08b0c67f295f6acd9ff422e13","key":"baz","value":0},
{"id":"95e7802ec6e00e803b780ad46cc473c4","key":"baz","value":0},
{"id":"66edc1870a7dfca239b022d74db37737","key":"boo","value":0},
{"id":"d5fff2a7b520c87180502a05847dfbd5","key":"boo","value":0},
{"id":"66edc1870a7dfca239b022d74db37737","key":"ga","value":0},
{"id":"66edc1870a7dfca239b022d74db37737","key":"grr","value":0},
{"id":"95e7802ec6e00e803b780ad46cc473c4","key":"moo","value":0}
]}
And when i call the second view ('counts'), i got
[info] [<0.58.0>] HTTP Error (code 500): {'EXIT',
{{badmatch,
{10,
[{obj,
[{"ar",1},
{"arg",1},
{"argh",1},
{"baz",2},
{"boo",2},
{"ga",1},
{"grr",1},
{"moo",1}]}]}},
[{couch_view,reduce,3},
{couch_httpd,handle_db_request,3},
{couch_httpd,handle_request,2},
{mochiweb_http,headers,4},
{proc_lib,init_p,5}]}}
[info] [<0.58.0>] 127.0.0.1 - - "GET /mydb/_view/tags/counts" 500
-
Oleg.