Python:构建 LRU 缓存

标签 python mongodb lru

我大约有 6,00,000 entries in MongoDB格式如下:

feature:category:count

在哪里

  • feature 可以是任何词,
  • 类别是正面的还是负面的,并且
  • count 表示某个特征在该类别的文档中出现的次数。

我想缓存前1000个元组,让我们这样说,以免每次都查询数据库。

如何在 Python 中构建 LRU 缓存?或者有任何已知的解决方案吗?

最佳答案

LRU cache在 Python3.3 中有 O(1) 的插入、删除和搜索。

该设计使用循环双向链接的条目列表(按从旧到新排列)和哈希表来定位各个链接。缓存命中使用哈希表查找相关链接并将其移动到列表的头部。缓存未命中删除最旧的链接并在链表的头部创建一个新链接。

这是 33 行非常基本的 Python 的简化(但速度很快)版本(仅使用简单的字典和列表操作)。它在 Python2.0 及更高版本(或 PyPy 或 Jython 或 Python3.x)上运行:

class LRU_Cache:

    def __init__(self, original_function, maxsize=1024):
        # Link structure: [PREV, NEXT, KEY, VALUE]
        self.root = [None, None, None, None]
        self.root[0] = self.root[1] = self.root
        self.original_function = original_function
        self.maxsize = maxsize
        self.mapping = {}

    def __call__(self, *key):
        mapping = self.mapping
        root = self.root
        link = mapping.get(key)
        if link is not None:
            link_prev, link_next, link_key, value = link
            link_prev[1] = link_next
            link_next[0] = link_prev
            last = root[0]
            last[1] = root[0] = link
            link[0] = last
            link[1] = root
            return value
        value = self.original_function(*key)
        if len(mapping) >= self.maxsize:
            oldest = root[1]
            next_oldest = oldest[1]
            root[1] = next_oldest
            next_oldest[0] = root
            del mapping[oldest[2]]
        last = root[0]
        last[1] = root[0] = mapping[key] = [last, root, key, value]
        return value


if __name__ == '__main__':
    p = LRU_Cache(ord, maxsize=3)
    for c in 'abcdecaeaa':
        print(c, p(c))

从 Python 3.1 开始,OrderedDict使实现 LRU 缓存变得更加简单:

from collections import OrderedDict

class LRU_Cache:

    def __init__(self, original_function, maxsize=1024):
        self.original_function = original_function
        self.maxsize = maxsize
        self.mapping = OrderedDict()

    def __call__(self, *key):
        mapping = self.mapping
        try:
            value = mapping[key]
            mapping.move_to_end(key)
        except KeyError:
            value = self.original_function(*key)
            if len(mapping) >= self.maxsize:
                mapping.popitem(False)
            mapping[key] = value
        return value

关于Python:构建 LRU 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4443920/

相关文章:

python - 简单建表sql适用于mysql和postgre,但在oracle中报错

python - 为什么这个 Python 脚本在多核上的运行速度比在单核上慢 4 倍

python - Django:进行数据库查询时出现UnboundLocalError

c++ - 生产代码中的 LRU 实现

caching - LRU 缓存如何符合 CAP 定理?

python - MySQLdb UPDATE 挂起

java - MongoDB Java驱动程序更新子文档

mongodb - 运行 Ubuntu 的设备上没有剩余空间

mongodb - 聚合管道返回错误结果与 CLI

Python 使用 OrderedDict 通过 LRU 进行基于大小的缓存