1
votes

I have an map function in a view in CouchDB that emits non-unique two array keys, for documents of type message, e.g.

2 array keys

The first position in the array key is a user_id, the second position represents whether or not the user has read the message.

This works nicely in that I can set include_docs=true and retrieve the actual documents. However, I'm retrieving duplicate documents in that case, as you can see above in the view results. I need to be able to write a view that can be queried to return unique messages that have been read by a given user. Additionally, I need to be able to efficiently paginate the resultset.

  1. notice in the image above that [66, true] is emitted twice for doc id 26a9a271de3aac494d37b17334aaf7f3. As far as I can tell, with the keys in my map function, I cannot reduce in such a way that unique documents will be returned.

  2. the next idea I had was to emit doc._id also in the map function and reduce with group_level=exact the result being:

    3 array keys

    now I am able to get unique document ids, but I cannot get the documents without doing a second query. And even in the case of a second query, it will require a lot of complexity to do pagination like this (at least I think so).

  3. the last idea I came up with is to emit the entire document rather than the doc._id in the third position in the array key, then I can access the entire document and likely paginate. This seems really brutish.

So my question is:

Is #3 above a terrible idea? Is there something I'm missing? Is there a better approach?

Thanks in advance.

1
Can you please show your map and reduce functions? It's not clear why you can't change the map function to not emit duplicates.Eli Stevens
@WickedGrey I think that might be the answer....Patrick Klingemann
@WicketdGrey was correct, The solution to my problem was to ensure that I emitted unique keys. I did that by keeping track of the keys that were emitted for each document and ensuring I didn't emit one more than once. That should've been obvious, but I'm learning :).Patrick Klingemann

1 Answers

0
votes

See @WickedGrey's comment to the question. The solution is to ensure that I never emit the same key twice for one document. I do this in the map function by keeping track of the keys as I emit them in an array, then skipping the emit if the key exists in the array.