Search code examples
graphredisgraph-theorysortedset

Redis: Implement Weighted Directed Graph


What's the best way to implement weighted graph using Redis?

We will mostly search for shortest paths over the graph (probably using the Dijkstra algorithm)

Currently we considered adding the edges to Redis

For each node, we will have the nodeId as the key and a sortedset of keys of referenced nodes the score of each nodeId in the sortedSet is the weight of the edge.

What do you think? Correct me if I am wrong but the only bummer here is that for each query for the next node in a sortedset we pay O(logn) instead of O(1)...

http://redis.io/commands/zrange


Solution

  • Getting the next item in a sorted set is only O(log(n)) if you are getting them out one at a time, in which case the latency of the connection to redis will be more of an issue than the complexity of the operation.

    For most operations on a graph you need to look at all the edges from a node, so it makes sense to load the whole set (or at least those with a suitable score) into local memory when you process the node. This will of course mean loading some edges that will not be followed because you have already found a suitable path, but since the sets are fairly small the cost of this will be far less than making a new call to redis for every edge that you do need.