python - 将字典的字典存储在 MySQL 数据库中

标签 python mysql

假设我有一个包含成对比较的字典:

 dict_of_dict = {"apple":{"apple":1, "orange":.5, "banana":.7}, "orange":{"orange":1, "apple": .3, "banana":.8}, "banana":{"banana":1, "apple":.7, "orange":.8}}

每个嵌入式词典可以包含约 20 万个条目。

将其存储在 MySQL 中的一种(糟糕的)方法是创建两个表 fruitfruit 映射,其中 fruit 存储一个 id每个水果和水果映射存储每个成对分数。

fruit 是一个包含 id 和 fruit 的两列表:

 fruit_id fruit
 0        apple
 1        orange
 2        banana

fruit mappingsfruit 的 ID 映射到每个成对比较的分数。

    fruit_id_A   fruit_id_B    score

       0               0         1        
       0               1        .5
       0               2        .7

...对于 fruit_ids 1 和 2 依此类推。您可以在处理 ~200k 条目时看到明显的问题。在实际应用中,我们不会有 ~200k**2 行,因为只比较了水果的一个子集,但即使假设 50,000 个水果获得的分数也将为我们提供 10,000,000,000 行。有人有更好的方法吗?

最佳答案

One (terrible) approach to storing this in MySQL would be to create two tables fruit and fruit mappings where fruit stores an id for each fruit and fruit mappings stores each pairwise score.

这不是一个糟糕的方法,而是关系数据库的明智方法。

当且仅当您的一组水果永远不会改变时,您可以只使用一个表来标识水果和一个 float 数组来保存它的所有分数。但是您需要知道数组的哪个索引映射到哪个其他水果。

我会选择明显的关系方法。拥有 200M 行有什么不好,如果您索引需要访问的列,也不会有性能问题。

关于python - 将字典的字典存储在 MySQL 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14465982/

相关文章:

php - SQLSTATE[42000] : Syntax error or access violation: 1064 Symfony 2. 7.3 应用

c# - 将绑定(bind)的组合框添加到数据 GridView

python - 将行值更改为多索引

python - 将 Flask 与 SQLAlchemy 和 Dash 一起使用

python - 沿着时间序列索引连接 pandas DataFrame

php - 如何在 mysqli 准备语句中使用多个内部连接和多个 WHERE 子句?

php - PHP 中的 json_encode 没有返回正确的结果

python - 如何管理访问 Django REST API 的权限?

python - 为什么我的 python 程序在使用调试器运行时不会抛出错误?

mysql - 转义字符串应该是 "unescaped"(MySQL、Node.js)吗?