Views and count distinct

Hi @socketman2016,

You could create a map function which emits client and user and reduce function _count.
Then call the view with group_level=2 and start key as [client, null] and end key as [client, “\uffff”] and count the number of row returned. This will be the number of distinct user for that client for startkey[0].

Map:
function (doc, meta) {
emit([doc.client, doc.user]);
}

reduce: _count

Query:
Querying for distinct user for client “a”.
stale=false&inclusive_end=true&full_set=true&group_level=2&startkey=%5B"a"%2C%20null%5D&endkey=%5B"a"%2C%20"%5Cu0fff"%5D

Result:
{“rows”:[
{“key”:[“a”,“Value1”],“value”:100},
{“key”:[“a”,“Value2”],“value”:100}
]
}
counting the number of rows gives the number of distinct user for client “a”.

1 Like