Guest User

Untitled

a guest
Jul 15th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. # Search usernames that begins with given phrase
  2. #
  3. # usernames: (username1, username2, ..)
  4. # userscore:<username>: float
  5. # user:obj: { id: int, username: string }
  6.  
  7. usernames_zset = "usernames"
  8.  
  9. def my_ord(c):
  10. return "%03d" % ord(c)
  11.  
  12. def get_score(s):
  13. return '0.' + ''.join(map(str, map(my_ord,s)))
  14.  
  15. def get_next_score(s):
  16. s_score = get_score(s)
  17. part0 = s_score[:4]
  18. c = s_score[4]
  19. next_c = str(int(c)+1)
  20. part1 = s_score[5:]
  21. return part0 + next_c + part1
  22.  
  23. def add_user(conn, username, score):
  24. # The User Object
  25. uid = conn.incr('user:idgen')
  26. conn.hset('user:obj:%d' % uid, 'id', username)
  27. # datastructures necessary to implement search
  28. conn.zadd(usernames_zset, username, score)
  29.  
  30. def add_test_data(conn):
  31. test_data = ('abc', 'ab', 'a', 'shekhar', 'shon', 'sh', 'zxcvbnmasdfghjklqwertyuiop0', 'zxcvbnmasdfghjklqwertyuiop00')
  32.  
  33. for username in test_data:
  34. score = get_score(username)
  35. add_user(conn, username, score)
  36.  
  37. import redis
  38. conn = redis.Redis()
  39.  
  40. add_test_data(conn)
  41.  
  42. # conn.zrange(usernames_zset, 0, -1) # Whole set
  43. a_score = get_score('a')
  44. b_score = get_next_score('a')
  45.  
  46. print 'Find all users starting with "a" -> INF'
  47. print conn.zrangebyscore(usernames_zset, a_score, 'INF')
  48. print 'Find all users starting with "a"'
  49. print conn.zrangebyscore(usernames_zset, a_score, b_score)
  50. print 'Find all users starting with "a" limit 2'
  51. print conn.zrangebyscore(usernames_zset, a_score, 'INF', 0, 2)
Add Comment
Please, Sign In to add comment