Last active
August 29, 2015 14:18
-
-
Save abhi-bit/b8ebaeae18d8261e6134 to your computer and use it in GitHub Desktop.
Use Couchbase views to populate leaderboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from couchbase import Couchbase | |
from couchbase import FMT_JSON | |
from couchbase.views.params import Query | |
from couchbase.views.iterator import View | |
import datetime | |
import json | |
from operator import itemgetter | |
import random | |
import string | |
import sys | |
# sample run | |
# $ python players.py <total_no_of_documents> <no_of_items_in_scoreboard> | |
# $ python players.py 10 2 | |
# Emit values from view: {"player_6": "4257305603", "player_7": "8833174376", "player_4": "8538191802", "player_5": "9022773031", "player_2": "6815851901", "player_3": "8273254294", "player_0": "1496448531", "player_1": "5460252310", "player_8": "8550782211", "player_9": "4004574951"} | |
# Top 2 blobs out of 10 | |
# [["player_5", "9022773031"], ["player_7", "8833174376"]] | |
def populate_documents(cb, doc_count): | |
for i in xrange(doc_count): | |
value = dict() | |
value['score'] = ''.join(random.choice(string.digits) | |
for _ in range(10)) | |
value['last_login'] = datetime.datetime.now().strftime("%X") | |
key = 'player_' + str(i) | |
try: | |
cb.set(key, value, format=FMT_JSON) | |
except: | |
pass | |
def gethighscore(cb, topscorecount): | |
q = Query(stale=False, inclusive_end=True) | |
response = dict() | |
for result in View(cb, "players", "highscores", query=q): | |
response[result.key] = result.value | |
print "All user blobs:", json.dumps(response) | |
return sorted(response.items(), key=itemgetter(1), | |
reverse=True)[:topscorecount] | |
def main(): | |
cb = Couchbase.connect(host="localhost", bucket="default") | |
doc_count = int(sys.argv[1]) | |
topscorecount = int(sys.argv[2]) | |
# view definition | |
#function (doc, meta) { | |
# emit(meta.id, doc.score); | |
# } | |
#} | |
populate_documents(cb, doc_count) | |
data = gethighscore(cb, topscorecount) | |
print "Top %d blobs out of %d" % (topscorecount, doc_count) | |
print json.dumps(data) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment