最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Couch DB filter by key and sort by another field - Stack Overflow

programmeradmin5浏览0评论

In couchdb I need to filter by key and which is done like this.

{
   "_id": "_design/test",
   "_rev": "6-cef7048c4fadf0daa67005fefe",
   "language": "javascript",
   "views": {
       "all": {
           "map": "function(doc) { if (doc.blogId) {emit(doc.key, doc);} }"
       }
   }
}

However the results should be ordered by another key (doc.anotherkey). So using the same function how do I achieve both filtering and ordering by another key.

Thank you

In couchdb I need to filter by key and which is done like this.

{
   "_id": "_design/test",
   "_rev": "6-cef7048c4fadf0daa67005fefe",
   "language": "javascript",
   "views": {
       "all": {
           "map": "function(doc) { if (doc.blogId) {emit(doc.key, doc);} }"
       }
   }
}

However the results should be ordered by another key (doc.anotherkey). So using the same function how do I achieve both filtering and ordering by another key.

Thank you

Share Improve this question asked Jan 19, 2012 at 10:52 DilshanDilshan 3,2414 gold badges41 silver badges51 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

If you only need to query by single key, you can use the following map:

function (doc) {
  if (doc.blogId) {
    emit([doc.key, doc.anotherkey], 1);
  }
}

and query for "KEY" with ?startkey=["KEY"]&endkey=["KEY",{}]&include_docs=true.

Here, according to the collation specification of CouchDB:

  • ["KEY"] is a value lesser than any ["KEY","OTHER"] value (because longer arrays sort after their prefixes), but greater than any ["KEY2","OTHER"] with "KEY2" < "KEY";
  • and ["KEY",{}] is a value greater than any ["KEY","OTHER"] value, if doc.otherkey is never a JSON object (because JSON objects es after any other JSON value), but lesser than any ["KEY2","OTHER"] with "KEY2" > "KEY".

Of course this is not limited to strings. Any type of value will work, as long as the collation is right.

Remember to URL encode the values in startkey and endkey. For example, using curl and assuming your database is "DB":

curl 'http://localhost:5984/DB/_design/test/_view/all?startkey=%5B%22KEY%22%5D&endkey=%5B%22KEY%22,%7B%7D%5D&include_docs=true'

Note that I've used the include_docs query parameter, instead of emitting the entire document with emit(..., doc), to save disk space. Query parameters are documented on CouchDB documentation.

To sort results in descending order, use the descending=true query parameter and swap the values of startkey and endkey as documented in the definitive guide book.

curl 'http://localhost:5984/DB/_design/test/_view/all?endkey=%5B%22KEY%22%5D&startkey=%5B%22KEY%22,%7B%7D%5D&include_docs=true&descending=true'
发布评论

评论列表(0)

  1. 暂无评论