I’m trying to "avoid updates" in CouchDB which seems to be the recommendation.
But I'm having trouble with being able to make a "reduce" view that returns only the latest value. In the data set below, the document a8f2298e5961b0ebf60e56022d253d2b
(where s=FooQuux) should basically never be returned, and could be deleted as a "cleanup" operation without impact.
I'd like to be able to do operations such as:
- Retrieve the value for
a
==>Bar
- this technique could work, using the
s
view, searching for[["a"], ["a",{}]]
with limit=1.
- this technique could work, using the
- Retrieve all values ==>
a=Bar, b=Quux
- Can I write a reduce to "strip out" documents that have an older timestamp?
And for the last two, I'm not sure if it's possible to write one map/reduce view that can do both, given the constraints.
- Get the string length for each user - group=1 ==
a=3, b=4
(not counting FooQuux) - Get the string length for all users - group=None ==
7
(not counting FooQuux)
Data: (this is a contrived example)
Given data: (where t is a timestamp, u is a username, s is a string)
- at timestamp 0, user
a
set valueFooQuux
- at timestamp 1, user
a
set valueBar
- at timestamp 2, user
b
set valueQuux
Database:
{
"_id": "_design/all",
"views": {
"s": {
"map": "function(doc) { if(doc.u) { emit([doc.u, doc.s, doc.t], doc.s); } }"
},
"slen": {
"map": "function(doc) { if(doc.u) { emit([doc.u, doc.s, doc.t], doc.s.length); } }",
"reduce": "_sum"
}
},
"language": "javascript"
}
{
"_id": "a8f2298e5961b0ebf60e56022d251ebd",
"t": 2,
"u": "b",
"s": "Quux"
}
{
"_id": "a8f2298e5961b0ebf60e56022d253a1b",
"t": 1,
"u": "a",
"s": "Bar"
}
{
"_id": "a8f2298e5961b0ebf60e56022d253d2b",
"t": 0,
"u": "a",
"s": "FooQuux"
}
[u, s, t]
) but with the document something like: { a: { t: 1, s: "Bar" } } … and then the reduce could collect the keys together, throwing out the old ones. So group=None would be { a: { s:Bar, t:1 }, b: {s:Quux, t:2} } and other group levels should work as expected… But for fetching a single "u", the limit=1 approach above would be best, as it wouldn't require a reduce. amirite? – Steven R. Loomis