简体   繁体   中英

CouchDB Ranking

I'm trying to figure out the best way of sorting by rank using couch db. I have my documents setup in a players db like so:

{
   "_id": "user2",
   "_rev": "31-65e0e5bb1eba8d6a882aad29b63615a7",
   "username": "testName",
   "apps": {
       "app1": {
           "score": 1000
       },
       "app2": {
           "score": 1000
       },
       "app3": {
           "score": 1000
       }
   }
}

The player can have multiple scores for various apps. I'm trying to figure out the best way to pull say the top 50 scores for app1.

I think one idea could be to store the score of each user for each app seperately. Like so: -

{"app":"app1","user":"user_id","score":"9000"}

The you could write a map function

emit([doc.app,doc.score],{_id:doc.user,score:doc.score})

and query the view like

/view_name?include_docs=true&startkey=["app1",{}]&endkey=["app1"]&descending=true

With this arrangement you have a view sorted by the score and the name of the app. Here are the results that you get.

{"total_rows":2,"offset":0,"rows":[

{"id":"61181c784df9e2db5cbb7837903b63f5","key":["app1",10000],"value":

{"_id":"5002539daa85a05d3fab16158a7861c1","score":10000},"doc": {"_id":"5002539daa85a05d3fab16158a7861c1","_rev":"1-8441f2f5dbaaf22add8969cea5d83e1b","user":"jiwan"}} ,

{"id":"7f5d53b2da8ae3bea8e2b7ec74020526","key":["app1",9000],"value":

{"_id":"336c2619b052b04992947976095f56b0","score":9000},"doc": {"_id":"336c2619b052b04992947976095f56b0","_rev":"3-3e4121c1831d7ecafc056e71a2502f3a","user":"akshat"}} ]}

You have score in value. User in doc.

Edit

Oops! I mistyped the startkey and endkey :) Notice that it is not startKey but startkey same for endkey . Also note that since descending is true we reverse the order of keys. It should work as expected now.

For more help check out

  1. This answer and
  2. This answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM