通过CouchDB中的键返回唯一值 [英] Return unique values by key in 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屋!