【问题标题】:Proper choice for a database consisting of a dictionary由字典组成的数据库的正确选择
【发布时间】:2017-04-18 09:44:10
【问题描述】:

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

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

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

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

我现在正在使用shelve,它非常易于使用。 但是,对于来自dict1 或dict2 的某个键的某个值,我将需要从主字典(dict)中获取所有键,这需要一些时间,我担心字典何时会要大得多,例如 50k 键,这将需要很长时间。 我读过sqlite3,这似乎是一个不错的选择,但我不知道它是否能满足我的需求。

除了 Python 程序之外,我真的不需要数据库可供其他程序访问(不过这会很好),但我需要它快速、稳定并且能够同时让多台计算机从中读取.谢谢!

【问题讨论】:

  • 与 SQL 相比,文档数据库可能更适合您的需求。

标签: python sqlite dictionary shelve


【解决方案1】:

我会选择一个支持原生 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

【讨论】:

  • 我已经做了一些研究,但我无法确定...根据您的经验,sqlite 和 postgresql 之间是否存在显着差异?谢谢回答
  • 我想说它们就像滑板车和 18 轮卡车一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2016-02-03
  • 2014-08-23
  • 2021-05-18
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
相关资源
最近更新 更多