Monday, 29 August 2016

Redis used as tree

Hello reader,

prerequisite of this blog :

  1. Basics of graphs and trees
  2. minimal exposure to Redis

So here goes the story ,

Intro 
We know redis is a simple key value in-memory database. However, there was an instance where I wanted to have a tree but still get the performance of redis.

I thought of sharing the solution if anyone would like to use it for their reference.

Idea's intro (Organizing your data )

In a way, the solution is pretty simple. Below is the image that would help you understand the solution.





Every node has a name without any special characters, and it should follow a specific format.

every entry in redis as you might know is key , value
and that we represent as nodename , nodevalue



Every node has value (say json as string)

key = node name
value = json string (that is the value we want to save in a node )

node name organized as below :
#parent1#parent2#parent3# ....#leafnode#


How to traverse

search string if used as below you can parse as a tree (used regex as supported by redis):
A#* all children of A

A#B#*
all children of B which is a child of node A and A is root
if the search would have been
*#B#*
all Children of node B and (B this time need not be root)

*#B#
Node B which might have parent


This is a pretty simple hack and works on an idea of creating node names with combination of node and edge names.

Statutory Warning 

Few things to think before actually using this solution:

If you have the independence, consider using solutions as graphical DBs such as like Neo4J orientdb, these are pretty good ones and we have a very vast libraries built around themselves. Though I used above solution for a brief period , I could very easily convince that graphical DB is much better solution.

It's a tree and not graph, so the chances of it's usage are limited.

And above all , it's just a hack :) beware of hacks always !!


Please comment and correct if you feel something feels not correct.