【问题标题】:Memcached with large objects (NetworkX graphs)带有大对象的 Memcached(NetworkX 图)
【发布时间】:2019-03-22 07:05:06
【问题描述】:

我有一个 NetworkX 图 (g),它有大约 25k 个节点和 125k 个边。我想使用 memcached 缓存 g,但 g 太大了。我最多可以将每个项目的 memcached 限制增加到 32MB,但不会这样做。

  1. 我是否应该尝试让它与 memcached 一起使用?

  2. 如果我希望能够存储最多有 1m 个节点和 10m 条边的 networkx 图,我还有哪些其他选择?

  3. 我如何在不 (a) 对图表一无所知的情况下,以及 (b) 以一种导致最小性能下降的方式将块重新组合在一起的情况下,对图表进行分块以使其更小。

    李>

我正在使用 python。附上创建图表的示例代码。

import sys
import pickle
import random
import networkx as nx
from django.core.cache import cache

def randstring(x=3):
    return ''.join([chr(random.randrange(65, 91)) for _ in range(x)])

class Qux(object):
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

for n, v in {1: 500, 2: 5000, 3: 50000}.items():
    g = nx.Graph()
    nodes = [Qux(randstring(), randstring()) for _ in range(v)]
    g.add_nodes_from(nodes)
    for node in g.nodes:
        num = random.randrange(25)
        edges = [(node, random.choice(nodes)) for _ in range(num)]
        g.add_edges_from(edges)

    print len(g.nodes), sys.getsizeof(pickle.dumps(g))
    cache.set('{}/graph'.format(n), g, 3600)

Memcached 控制台输出 (memcached -I 32M -vv)

<20 new auto-negotiating client connection
20: Client using the ascii protocol
<20 set :1:1/graph 1 3600 130678 
>20 STORED
<20 delete :1:2/graph
>20 NOT_FOUND
<20 delete :1:3/graph
>20 NOT_FOUND

【问题讨论】:

  • 您找到解决方法了吗?

标签: python django memcached networkx


【解决方案1】:

如果您查看 NetworkX 的代码,图表只不过是 python 字典。如果您需要的唯一功能是访问节点和边,那么使用 dicts 构建图形并将文件转换为 JSON 可以让您缓存图形。 将边添加到无向加权图的代码本质上是这样的:

G_New = {}
for edge in edges:
    try:
        G_New[edge['node1'].update({edge['node2']: edge['weight']})
    except KeyError:
        G_New[edge['node1']] = {edge['node2']: edge['weight']}
    try:
        G_New[edge['node2']].update({edge['node1']: edge['weight']})
    except KeyError:
        G_New[edge['node2']] = {edge['node1']: edge['weight']}

之后就是一个简单的json.dumps(G_New)。对于较大的图表,您可以将 dict 拆分为较小的组件,并将每个组件托管在 memcache 上。这样How to split dictionary into multiple dictionaries fast

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多