在 CouchDB 中按键返回唯一值 [英] Return unique values by key in CouchDB

查看:19
本文介绍了在 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天全站免登陆