计算ZODB中保存的BTree的len()需要很多时间

2024-05-20 15:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用ZODB和BTrees来存储大量数据(数百万个键)。我想得到根字典(它是一个BTree)中确切的条目数。正如我注意到的那样,len()调用.keys()的结果需要很长时间(至少几十分钟,老实说,我从来没有等到它在数据集变大时结束)。在

import ZODB
from BTrees.OOBTree import BTree

connection = ZODB.connection('database.fs')
dbroot = connection.root()

if not hasattr(dbroot, 'dictionary'):
    dbroot.dictionary = BTree()

# much data is added and transactions are commited

number_of_items = len(dbroot.dictionary.keys()) # takes very long time

我定期打包数据库。在

我不认为这与问题有关,但是dbroot.dictionary包含其他BTree作为值。在


Tags: 数据fromimportdictionarylen字典条目keys
1条回答
网友
1楼 · 发布于 2024-05-20 15:00:47

您正在调用.keys()方法,该方法必须加载并生成所有键的完整列表。这需要很多时间。在

你可以问树本身的长度:

number_of_items = len(dbroot.dictionary)

这仍然需要load all the buckets themselves(键块)来询问每个键的长度,因此仍然需要加载大量数据,只是不生成列表。在

我们总是避免尝试获取直接长度;^{} object更适合“手动”跟踪长度。该对象正在完全解决ZODB冲突。每次向dbroot.dictionary添加元素时,都要向BTree.Length对象添加一个计数,并使其保持计数:

^{pr2}$

然后通过调用对象读取长度:

length = dbroot.dict_length()  

相关问题 更多 >