views:

195

answers:

1

Hello,

what is the best practice to sort/order multiple documents by user defined order (position) in CouchDB?

Solutions I thought about:

  1. Every document has a "position" value, starting from 1 to n. The view would emit this value. Problem: If one document is sorted, all other documents with a greater position have to updates. This could be hundreds of updates. Hmm.

  2. Every document knows it's previous document's _id. The order is generated after retrieving the view.

  3. The is a special document storing the _ids of all documents that should be sorted in an array. We sort in this solution again after retrieving the view.

Is the any other or more simple solution? In a RDBMS solution 1. was the best practice and a simple update query did the position update of all documents.

Best regards, Bernd

+3  A: 

You could use a float value, for example between 0.0 and 1.0 for the position. To move Document A in between documents B and C then you just set its new position to (B.position + C.position) / 2.0 (i.e. the average of their positions).

jhs
Excellent answer. See http://books.couchdb.org/relax/reference/recipes#Ordering%20Lists for a more detailed discussion of the proposed solution.
Jan Lehnardt
Well, that's an interesting solution. Maybe it's a good idea to to test the limit of precision and the number of possible movements. I will post it here.
Bernd
In JavaScript the precision problem starts about after the 16th calculation of the average at the same position. In PHP the limit is only the result length. So this work great on sporadic changes to the position and with a fix for long float values.
Bernd
Yeah, I'd have a async background task that would remove decimals when a user is inactive to make this really robust.
Jan Lehnardt