-6ren">
gpt4 book ai didi

couchdb - 通过CouchDB中的键返回唯一值

转载 作者:行者123 更新时间:2023-12-03 16:08:15 24 4
gpt4 key购买 nike

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

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=“key2”将返回['anotherval','andanother']

最佳答案

As suggested in the CouchDB definitive guide,您应该将想要唯一的值放在键中,然后使用group=true查询reduce函数。

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

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函数可能是:
_sum

然后用 group=true&startkey=["key2"]&endkey=["key2",{}]查询得到:
{"rows":[
{"key":["key2","anotherval"],"value":1},
{"key":["key2","andanother"],"value":2}
]}

关于couchdb - 通过CouchDB中的键返回唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5456682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com