Sorting CouchDB Views By Value

前端 未结 7 1513
独厮守ぢ
独厮守ぢ 2020-12-04 08:52

I\'m testing out CouchDB to see how it could handle logging some search results. What I\'d like to do is produce a view where I can produce the top queries from the results

7条回答
  •  独厮守ぢ
    2020-12-04 09:05

    This came up on the CouchDB-user mailing list, and Chris Anderson, one of the primary developers, wrote:

    This is a common request, but not supported directly by CouchDB's views -- to do this you'll need to copy the group-reduce query to another database, and build a view to sort by value.

    This is a tradeoff we make in favor of dynamic range queries and incremental indexes.

    I needed to do this recently as well, and I ended up doing it in my app tier. This is easy to do in JavaScript:

    db.view('mydesigndoc', 'myview', {'group':true}, function(err, data) {
    
        if (err) throw new Error(JSON.stringify(err));
    
        data.rows.sort(function(a, b) {
            return a.value - b.value;
        });
    
        data.rows.reverse(); // optional, depending on your needs
    
        // do something with the data…
    });
    

    This example runs in Node.js and uses node-couchdb, but it could easily be adapted to run in a browser or another JavaScript environment. And of course the concept is portable to any programming language/environment.

    HTH!

提交回复
热议问题