通过CouchDB中的键返回唯一值 [英] Return unique values by key in CouchDB

查看:69
本文介绍了通过CouchDB中的键返回唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CouchDB中是否可以执行以下操作?一种通过给定键返回唯一,不同值的方法?

Is there a way to do the following in CouchDB? A way to return unique, distinct values by a given key?

SELECT DISTINCT field FROM table WHERE key="key1"

'key1' => 'somevalue'
'key1' => 'somevalue'
'key2' => 'anotherval'
'key2' => 'andanother'
'key2' => 'andanother'

例如:

http://localhost:5984/database/_design/designdoc/_view /distinctview?key = "key1"将返回['somevalue']

http://localhost:5984/database/_design/designdoc/_view/distinctview?key="key1" would return ['somevalue']

http://localhost:5984/database/_design/designdoc/_view /distinctview?key = "key2"将返回['anotherval','andanother']

http://localhost:5984/database/_design/designdoc/_view/distinctview?key="key2" would return ['anotherval', 'andanother']

推荐答案

如建议CouchDB权威指南,您应该将想要唯一的值放在键中,然后使用group=true查询reduce函数.

As suggested in the CouchDB definitive guide, you should put the values you want to be unique in the key, then query the reduce function with group=true.

例如,假设keyfield是带有"key1"和"key2"的字段,而valuefield是带有值的字段,则您的映射函数可能是:

For example, given that keyfield is the field with "key1" and "key2" and valuefield is the field with the values, your map function could be:

function(doc) {
  // filter to get only the interesting documents: change as needed
  if (doc.keyfield && doc.valuefield) {
    /*
     * This is the important stuff:
     * 
     *  - by putting both, the key and the value, in the emitted key,
     *    you can filter out duplicates
     *    (simply group the results on the full key);
     * 
     *  - as a bonus, by emitting 1 as the value, you get the number
     *    of duplicates by using the `_sum` reduce function.
     */
    emit([doc.keyfield, doc.valuefield], 1);
  }
}

您的reduce函数可能是:

and your reduce function could be:

_sum

然后使用group=true&startkey=["key2"]&endkey=["key2",{}]查询给出:

{"rows":[
{"key":["key2","anotherval"],"value":1},
{"key":["key2","andanother"],"value":2}
]}

这篇关于通过CouchDB中的键返回唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆