Reputation: 146
I want to use redisgraph-py to load a saved graph back into a Graph object. How do I load data with redis-py that's stored as type graphdata
?
I'm running the redisgraph docker image and have no problems seeing the graph among the keys. I'm new to redis and was trying to just use r.get('random')
to load the saved graph but I see from the top answer here that I need to use the right method to extract the right type of value with redis-py.
from io import BytesIO
from pprint import pprint
import numpy as np
import redis
from redisgraph import Node, Edge, Graph
def _array2bytes(arr):
with BytesIO() as b:
np.save(b, arr)
return b.getvalue()
def _bytes2array(byts):
return np.load(BytesIO(byts))
def _add_nodes(r, graph, n_nodes):
nodes = []
for k in range(n_nodes):
n = Node(label="node")
graph.add_node(n)
nodes.append(n)
_id = n.alias
feat = np.random.rand(1,100,7,7)
feat_bytes = _array2bytes(feat)
r.set(_id, feat_bytes)
return nodes
def _add_edges(nodes, graph, edge_prob):
edges = []
for k, node0 in enumerate(nodes):
for kk, node1 in enumerate(nodes):
if np.random.rand() < edge_prob:
edge = Edge(node0, "adjacent_to", node1)
graph.add_edge(edge)
edges.append(edge)
return edges
def _create_random_graph(r, graphname="random", n_nodes=1000, edge_prob=0.1):
redis_graph = Graph(graphname, r)
nodes = _add_nodes(r, redis_graph, n_nodes)
edges = _add_edges(nodes, redis_graph, edge_prob)
return redis_graph
def _save_graph():
r = redis.Redis(host='localhost', port=6379)
g = _create_random_graph(r)
g.commit()
return r
def _load_graph(r):
# The graph is saved under the key 'random'
print(r.type('random'))
def _main():
r = _save_graph()
_load_graph(r)
if __name__ == "__main__":
_main()
I'm seeing graphdata
, and I don't know how to load this type of data using redis-py or redisgraph-py. Can't find anything in the docs either.
Upvotes: 2
Views: 692
Reputation: 879
Currently redisgraph-py can't re-creating a Python graph object from a Redis key containing a graph.
To implement this the module (redisgraph-py) would have to retrieve all nodes by issuing a query:
MATCH (n) RETURN n
And create a redisgraph-py Node object form each, in addition it would have to issue a second query retrieving all relationships
MATCH (n)-[r]->(m) RETURN n,r,m
And create a redisgraph-py edge object from each.
I think if we would go that way, it would make sense to implement an interface / framework similar to NetworkX.
Upvotes: 1