CouchDB View Sort by Value

282 views Asked by At

I am looking for a poor perfomance solution to sort my couchdb view by value (because large data). I am using on my NodeJS Application the "nano" package to get the database/view connection.

I created a CouchDB View Map Function configure a key value pair and the Reduce to _count:

function (doc) {
  emit(doc.msg, 1);
}

To get my View i am using:

alice.view('VIEWNAME', 'INDEXNAME', {'group': true).then((body) => { 
body.rows.forEach((doc) => {
  console.log(doc.key + " " + doc.value);
 }
}

The View returns for example "Hello" as doc.key and "155" as doc.value. So i have 155 Documents with the Key Hello. Now i want to sort my View DESC from Value:

Hello 155
Foo   140
Bar   100

But the only Sorted Version of my View is by Key i get my View sorted by Key ASC.

I tried serval solution on NodeJS side but i dont want to lose much perfomance.

2

There are 2 answers

2
Jonathan Hall On

You cannot do this. Views, by nature, are sorted by key only. The solution is to create a second view that sorts by a different key.

0
blizzer On

I build a work around on NodeJS Side:

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

Im not 100 percent satisfied, but the solution helped me. I still cannot estimate how much perfomanace the sorting takes on the NodeJS side