计算 couchdb 文档中的标签数

count number of tags in a couchdb document

我有一个类似这样的简单文档设计...

{
  _id: "something", 
  type: "post", 
  title: "A Title",
  content: "A Blog Content",
  tags: ["newtag", "oldtag", "bluetag", "youtag"]
}

所以每个文档都会有一个"tags"的数组。我想要做的是创建一个视图来计算标签的使用次数。所以它会搜索所有文档,发出标签,然后按键添加它们。示例...

Doc1
{
  _id: "something",
  type: "post",
  title: "A title",
  content: "Blog Content",
  tags: ["oldtag", "newtag", "bluetag", "youtag"]
}
Doc2
{
  _id: "domethin",
  type: "post",
  title: "another title",
  content: "another post",
  tags: ["oldtag", "notag", "whytag"]
}

鉴于我需要的东西 "oldtag" : 2, "notag": 1, "whytag": 1, ...

但我似乎想不通。我尝试使用....

"map": "function(doc) {if(doc.type == 'post') { for(var i = 0, l doc.tags.length; i < l; i++) { emit(doc.tags[i], 1); } } }",
"reduce": "_count"

但这只是给了我...

{"rows":[ {"key":null,"value":20} ]}

有人知道怎么做吗?我很困。谢谢。

您认为 javascript 无效。

var i=0; l doc.tags l 应该分配给 doc.tags.length

查看修复版本:

{
  "_id": "_design/tagcount",
  "_rev": "1-d14c9d06e652ad23df1044ffbca9d85f",
  "views": {
    "count": {
      "reduce": "_count",
      "map": "function (doc) {\n  if(doc.type== 'post') { \n    for(var i = 0, l= doc.tags.length; i < l; i++) { emit(doc.tags[i], 1); } } \n}"
    }
  },
  "language": "javascript"
}

此外,您需要指定 reduce :

http://localhost:5984/<db>/_design/<design>/_view/<viem>?limit=20&reduce=true&group=true

注意:将 替换为其实际值。