query_cache_snippets.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # -*- coding: utf-8 -*-
  2. class QueryApi(object):
  3. def __init__(self, memory_cache, reverse_index_cluster):
  4. self.memory_cache = memory_cache
  5. self.reverse_index_cluster = reverse_index_cluster
  6. def parse_query(self, query):
  7. """Remove markup, break text into terms, deal with typos,
  8. normalize capitalization, convert to use boolean operations.
  9. """
  10. ...
  11. def process_query(self, query):
  12. query = self.parse_query(query)
  13. results = self.memory_cache.get(query)
  14. if results is None:
  15. results = self.reverse_index_cluster.process_search(query)
  16. self.memory_cache.set(query, results)
  17. return results
  18. class Node(object):
  19. def __init__(self, query, results):
  20. self.query = query
  21. self.results = results
  22. class LinkedList(object):
  23. def __init__(self):
  24. self.head = None
  25. self.tail = None
  26. def move_to_front(self, node):
  27. ...
  28. def append_to_front(self, node):
  29. ...
  30. def remove_from_tail(self):
  31. ...
  32. class Cache(object):
  33. def __init__(self, MAX_SIZE):
  34. self.MAX_SIZE = MAX_SIZE
  35. self.size = 0
  36. self.lookup = {}
  37. self.linked_list = LinkedList()
  38. def get(self, query):
  39. """Get the stored query result from the cache.
  40. Accessing a node updates its position to the front of the LRU list.
  41. """
  42. node = self.lookup[query]
  43. if node is None:
  44. return None
  45. self.linked_list.move_to_front(node)
  46. return node.results
  47. def set(self, results, query):
  48. """Set the result for the given query key in the cache.
  49. When updating an entry, updates its position to the front of the LRU list.
  50. If the entry is new and the cache is at capacity, removes the oldest entry
  51. before the new entry is added.
  52. """
  53. node = self.map[query]
  54. if node is not None:
  55. # Key exists in cache, update the value
  56. node.results = results
  57. self.linked_list.move_to_front(node)
  58. else:
  59. # Key does not exist in cache
  60. if self.size == self.MAX_SIZE:
  61. # Remove the oldest entry from the linked list and lookup
  62. self.lookup.pop(self.linked_list.tail.query, None)
  63. self.linked_list.remove_from_tail()
  64. else:
  65. self.size += 1
  66. # Add the new key and value
  67. new_node = Node(query, results)
  68. self.linked_list.append_to_front(new_node)
  69. self.lookup[query] = new_node