Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How order a view result by reduced value? CouchDB

Can I order the result of a view by the value, returned by reduced?

{
    "rows": [
        {"key":"bob","value":2},
        {"key":"john","value":3},
        {"key":"zztop","value":1}
     ]
}

I wanna a result like this:

{
    "rows": [
        {"key":"zztop","value":1},
        {"key":"bob","value":2},
        {"key":"john","value":3}

     ]
}
like image 326
Lucas Renan Avatar asked Mar 12 '10 20:03

Lucas Renan


2 Answers

you just want to sort the rows array by the value property of each object? you can specify a custom comparison method for the js sort method.

myResult.rows.sort(function (a, b) {
    return parseInt(a.value,10) - parseInt(b.value,10);
});

parameters a and b will each be an entry from the rows array. the method returns an int value of greather than 0, 0, or less than zero. greater than 0 means a should be ordered before b, the opposite for less than 0, and 0 means they are equal.

like image 64
lincolnk Avatar answered Sep 26 '22 03:09

lincolnk


I would just build it into the key...

{"key": [1, "zztop"], "value": "whateverYouWant"},
{"key": [2, "bob"], "value": "whateverYouWant"},
{"key": [3, "john"], "value": "whateverYouWant"}

In order to search for a specific key, use a startkey/endkey query like this:

http://XXXXXX/database/_design/name/_view/name?startkey=[[0,"zztop"]]&endkey=[[999,"zztop"]]

As long as your value is numerical, just make the endkey larger than the largest possible value and this query should return the results for "zztop."

It's sloppy, but I have yet to find a better CouchDB sorting method. All-in-all, you might be better sorting in your application.

like image 37
MitchB Avatar answered Sep 22 '22 03:09

MitchB