gpt4 book ai didi

python - 正确选择由字典组成的数据库

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:51 24 4
gpt4 key购买 nike

我有一本大字典,其格式如下:

dict["randomKey"]=[dict1,dict2,int,string]

可能会有数万个 key 。 dict1 本身有大约 100 个键。

问题是:我需要将这本字典存储在服务器上并由多台计算机读取。最好的格式是什么?

我现在使用shelve,它非常容易使用。但是,我需要从主字典(dict)中获取 dict1dict2 中某个键的某个值的所有键,这需要一些时间并且我担心当字典变得更大时,比如 50k 个键,这将需要很长时间。我读过有关 sqlite3 的内容,它似乎是一个不错的选择,但我不知道它是否是满足我需求的良好解决方案。

我真的不需要数据库能够被Python程序之外的其他程序访问(虽然这会很好),但我需要它快速、稳定并且能够让许多计算机同时读取它。谢谢!

最佳答案

我会选择一个具有原生 json 支持的数据库,它可以有效地在 json 字典中搜索。我喜欢 PostgreSQL:

数据表:

create table dict (
key text primary key,
dict1 jsonb not null default '{}',
dict2 jsonb not null default '{}',
intval integer not null,
strval text not null
);

用一些示例值填充它:

insert into dict
select
i::text,
(select
jsonb_object(
array_agg('k'||v::text),
array_agg('v'||(v+i)::text)
) from generate_series(1,1000) as v
),
(select
jsonb_object(
array_agg('k'||v::text),
array_agg('v'||(v+i)::text)
) from generate_series(1,1000) as v
),
i,
i::text
from generate_series(1,10000) as i;

获取 dict1 中键 k6 值为 v134 的键:

select key from dict where dict1 @> '{"k6":"v134"}';
key
-----
128
(1 row)

Time: 232.843 ms

如果您的表非常大,您甚至可以对字典列建立索引,以实现更快的搜索。但这些索引将比表本身大,数据库可以决定不使用它们更安全:

create index dict_dict1_idx on dict using gin(dict1);
create index dict_dict2_idx on dict using gin(dict2);

如果您知道这样做是有益的,您可以强制数据库使用索引:

set enable_seqscan=off;
select key from dict where dict1 @> '{"k6":"v134"}';
key
-----
128
(1 row)

Time: 8.955 ms

关于python - 正确选择由字典组成的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43468755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com