|
| 1 | +""" |
| 2 | +Redis storage |
| 3 | +""" |
| 4 | +import redis |
| 5 | +from redisgraph import Node, Edge, Graph |
| 6 | +from .base import BaseGraph |
| 7 | + |
| 8 | + |
| 9 | +class RedisGraph(BaseGraph): |
| 10 | + """ |
| 11 | + Handles storing a collection of models in RedisGraph |
| 12 | + """ |
| 13 | + def __init__(self, host, port=6379): |
| 14 | + """ |
| 15 | + :type host str |
| 16 | + :type port int |
| 17 | + """ |
| 18 | + super(RedisGraph, self).__init__() |
| 19 | + |
| 20 | + self.host = host |
| 21 | + self.port = port |
| 22 | + |
| 23 | + self.logger.info('Using redis: %s:%d', host, port) |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def encode_properties(properties): |
| 27 | + """ |
| 28 | + :type properties dict |
| 29 | + :rtype: dict |
| 30 | + """ |
| 31 | + ret = dict() |
| 32 | + |
| 33 | + # redisgraph library does not encode quotes |
| 34 | + # (John_Faxe_Jensen:Person{name:\"John \"Faxe\" Jensen\",birthDate:1965,height:1.78}) |
| 35 | + for key, value in properties.items(): |
| 36 | + ret[key] = value.replace('"', '\\"') if isinstance(value, str) else value |
| 37 | + |
| 38 | + return ret |
| 39 | + |
| 40 | + @classmethod |
| 41 | + def model_to_node(cls, model): |
| 42 | + """ |
| 43 | + :type model grapher.models.BaseModel |
| 44 | + :rtype: Node |
| 45 | + """ |
| 46 | + properties = dict(name=model.get_name()) |
| 47 | + properties.update(model.properties) |
| 48 | + |
| 49 | + return Node( |
| 50 | + alias=model.get_node_name(), |
| 51 | + properties=cls.encode_properties(properties) if properties else None, |
| 52 | + ) |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def model_to_edges(cls, model): |
| 56 | + """ |
| 57 | + :type model grapher.models.BaseModel |
| 58 | + :rtype: list[Edge] |
| 59 | + """ |
| 60 | + for (relation, target, properties) in model.get_all_relations(): |
| 61 | + # Edge(john, 'visited', japan, properties={'purpose': 'pleasure'}) |
| 62 | + yield Edge( |
| 63 | + src_node=Node(alias=model.get_node_name()), |
| 64 | + relation=relation, |
| 65 | + dest_node=Node(alias=target), |
| 66 | + properties=cls.encode_properties(properties) if properties else None |
| 67 | + ) |
| 68 | + |
| 69 | + def _get_graph(self, graph_name): |
| 70 | + """ |
| 71 | + :type graph_name str |
| 72 | + :rtype: Graph |
| 73 | + """ |
| 74 | + # https://github.com/RedisLabs/redisgraph-py#example-using-the-python-client |
| 75 | + redis_graph = Graph( |
| 76 | + name=graph_name, |
| 77 | + redis_con=redis.Redis(self.host, self.port) |
| 78 | + ) |
| 79 | + |
| 80 | + # add all nodes |
| 81 | + for model in self.models: |
| 82 | + redis_graph.add_node(self.model_to_node(model)) |
| 83 | + |
| 84 | + # and now add edges |
| 85 | + for model in self.models: |
| 86 | + for edge in self.model_to_edges(model): |
| 87 | + try: |
| 88 | + # add target node if needed |
| 89 | + # we may want to refer to a node that was not indexed above |
| 90 | + # e.g. English player in a Spanish club |
| 91 | + if edge.dest_node.alias not in redis_graph.nodes: |
| 92 | + node = Node( |
| 93 | + alias=edge.dest_node.alias, |
| 94 | + properties={'name': str(edge.dest_node.alias).split(':')[0]} |
| 95 | + ) |
| 96 | + redis_graph.add_node(node) |
| 97 | + self.logger.info('Adding missing node: %s', edge.dest_node.alias) |
| 98 | + |
| 99 | + redis_graph.add_edge(edge) |
| 100 | + except KeyError: |
| 101 | + print(model) |
| 102 | + # graph can be not complete, some nodes can be missing despite the relation |
| 103 | + self.logger.error('add_edge failed', exc_info=True) |
| 104 | + |
| 105 | + # assert valid nodes |
| 106 | + # for _, node in redis_graph.nodes.items(): |
| 107 | + # print(node.alias, node.properties) |
| 108 | + # print(str(node)) |
| 109 | + return redis_graph |
| 110 | + |
| 111 | + def dump(self, graph_name): |
| 112 | + """ |
| 113 | + Return a redisgraph command that would create a graph |
| 114 | +
|
| 115 | + :type graph_name str |
| 116 | + :rtype: str |
| 117 | + """ |
| 118 | + redis_graph = self._get_graph(graph_name) |
| 119 | + |
| 120 | + # https://oss.redislabs.com/redisgraph/#with-redis-cli |
| 121 | + # copied from redisgraph/client.py (commit function) |
| 122 | + query = '' |
| 123 | + |
| 124 | + for _, node in redis_graph.nodes.items(): |
| 125 | + query += str(node) + ',' |
| 126 | + |
| 127 | + for edge in redis_graph.edges: |
| 128 | + query += str(edge) + ',' |
| 129 | + |
| 130 | + # Discard leading comma. |
| 131 | + if query[-1] == ',': |
| 132 | + query = query[:-1] |
| 133 | + |
| 134 | + # encode " |
| 135 | + query = query.replace('"', '\\"') |
| 136 | + |
| 137 | + return 'GRAPH.QUERY {name} "CREATE {graph}"'.format(name=graph_name, graph=query) |
| 138 | + |
| 139 | + def store(self, graph_name): |
| 140 | + """ |
| 141 | + Store the graph in Redis |
| 142 | +
|
| 143 | + :type graph_name str |
| 144 | + """ |
| 145 | + redis_graph = self._get_graph(graph_name) |
| 146 | + |
| 147 | + # and save it |
| 148 | + self.logger.info('Committing graph with %d nodes and %s edges', |
| 149 | + len(redis_graph.nodes), len(redis_graph.edges)) |
| 150 | + |
| 151 | + try: |
| 152 | + redis_graph.delete() |
| 153 | + except redis.exceptions.ResponseError as ex: |
| 154 | + # Graph was not found in database. |
| 155 | + self.logger.info(ex) |
| 156 | + |
| 157 | + redis_graph.commit() |
| 158 | + |
| 159 | + redis_graph.redis_con.execute_command('SAvE') |
| 160 | + self.logger.info('Committed and saved') |
0 commit comments