Fork me on GitHub

Graph Redis

Getting started

In this part we will show you how to build this graph using Graph/Redis, and we will see how to apply some of the base commands and the algorithms on this sample

First we need to add the nodes a, b, c, d and e

To do so, we use the command gnode as in the following example:

gnode graph1 a
gnode graph1 b
gnode graph1 c
gnode graph1 d
gnode graph1 e

or we can use gnode to add multiple nodes at once, like in this example:

gnode graph1 a b c d e

graph1 didn't exist before, but it has been created once we added the first node to it.

By the end of running add the nodes, our graph looks like this

To add weighted edges to the graph, we use the command gedge which takes 4 paramters: graph_name node1 node2 edge_value

Example:

gedge graph1 a b 1
gedge graph1 b c 1
gedge graph1 c d 1
gedge graph1 d e 1
gedge graph1 e a 3
gedge graph1 a d 20

And the result will be exactly as in the graph depicted at the top of the page

So let's now play with some commands, and see what Graph/Redis can do

Listing the neighbours

Let's assume we want to list the neighbour nodes of some node, let's say a in our example. neighbour nodes of a are the nodes which have direct edge with the node a. To list the neighbours, we use the command gneighbours like this. gneighbours graph1 a which will return a list of the following values:
1) b
2) d
3) e

Common neighbours

Let's assume we want to list the common neighbours between two difference nodes. For that, we use the command gcommon. For example, to know the common nodes between a and d we run the command gcommon graph1 a d which will return a list that consists only of e, as it's clear from the graph that it's the only common neighbour of a and d.

Directed Graphs

With graph-redis, you can also construct directed graphs, that affect the return values of some commands

To set the graph as directed, call gsetdirected command before you add any edges

Example
gnode graph1 a b c
gsetdirected graph1
gedge graph1 a b 10
gedge graph1 c a 2
gneighbours graph1 a # Returns['b']
gneighbours graph1 c # Returns['a']
gneighbours graph1 b # Returns[]
gincoming graph1 b # Returns['a']

Algorithms

Graph/Redis supports also some algorithms on graphs, here we will show some:

Minimum Spanning Tree

To find the minimum spanning tree of a connected graph, you can use the command gmintree.

This command takes two paramters: the graph name, and another graph name in which the minimum spanning tree will be saved.

for example, running gmintree graph1 graph2 on the previous graph1 will result in the following graph(tree) being saved in graph2:

It's worth mentioning that Graph/Redis minimum spanning tree command uses Prim's algorithm.

To see the full list of the commands and the algorithms supported by Graph/Redis, please check the commands page