Using c# to connect To Neo4j (Graph database) Part 1

5 במרץ 2013

3 תגובות

Hey everyone.

Graph database, everyone hears about it, everyone talks about it and many solutions out there started to look into it in order to improve performance and start answering questions where relational databases fails to answer (or with really bad performance).

There are many graph databases that anyone can use, in my tests I have look at AllegroGraph, FlockDB, Trinity and my favorite and the one I will talk about now Neo4j. I know there are more graph databases that I haven’t really looked at like GraphDB or Infinite Graph but I had to chose something, and those I chose seemed from high level the best candidates.

I have decided that Neo4j fulfill most of my requirements, I am not going to get into in this post why, maybe I will do it in a later post, but I just wanted to say that Neo4j is the most mature of all of them with strong community and many projects using it in production (!).

So, lest start, first you need to install Neo4j from here, easy step up and soon you are ready to go, second, open the console and start the server (of course when you close the console the server will close as well). Finally we can start connecting to the Neo4j sever from our code.

Neo4j was written in Java and writing in java is the easiest way to connect to it. We as a .NET developers have 3 options

  1. Write the code that connect to the database in java and wrap in as a service that .NET can consume, this design has many disadvantage like overhead performance, need to change in 2 places in case of a bug and so on. Having said all that, there will be certain situations that this design will fit the best, especially if you would like to tweak everything by yourself and the next 2 solution will not give you this option.
  2. Use .Net drivers, There are some .net drivers that can help you working with Neo4j, many uses them but didn’t like them much, at first they don’t come from the Neo4j team (even though one has a reference from Neo4j website) meaning those .NET drivers can be abandon at some point and no one will continue to support them. Second, both drivers I have checked Neo4JClient and Neo4JD have bugs,  mostly small one’s but still every time you encounter a bug that you found on the driver, you ask yourself why use the driver at all. If you are learning or just trying it out using those drivers can fit you, else use the 3rd option (or at least until those drivers grow up and be more production ready and bugs free).
  3. Use Neo4j restful API, you can use a Restful web service for common methods like POST a new database node or a new database relation, GET for read nodes from the database and so on and for not common uses you can use Cypher Query Language (We will look at it later). This is the option I chose, working with the main setback is you have to learn cypher but this is not hard and with much documentation online if you have a problem, I found it worth.

Let’s talk a little bit about what is a Neo4j node, the easiest way to explain it is “A Graph —records data in→ Nodes —which have→ Properties”. Let’s say I would like to represents humans, each node will be a human and each human will have its own properties. So for each human a node in the database will be created with his own properties. The properties in a now a are set of key value pairs of primitives or an array of one primitive type (so no complex structure).

Another key element in a graph database is relationships and again “Nodes —are organized by→ Relationships —which also have→ Properties” which means that nodes are connected using relationships and the relationship as well has properties the same as nodes.

So, let’s start coding:

The way I chose to connect to the Neo4j server is using Restful service, so I have created a helpful method which I am going to use.

private HttpClient CreateHttpClient()
{
    HttpClient client = new HttpClient();
    //client.BaseAddress = new Uri(Your_Server_Name);

    // Add an Accept header for JSON format.
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

    return client;
}

As you can see the Neo4j Restful service expects to receive data in Json format.

Second, let’s add a new node to the graph database

private async Task CreateEntity(Entity entity)
{
    HttpClient httpClient = CreateHttpClient();

    HttpContent stringContent = new StringContent(
        JsonConvert.SerializeObject(entity));
    HttpResponseMessage av = await httpClient.PostAsync
        ("db/data/node", stringContent);

    if (av.IsSuccessStatusCode)
    {
        string responseBody = await av.Content.ReadAsStringAsync();
        // My simple method that reads the database id that was 
        //given to the new entity
        entity.Id = GetIdFromRespond(responseBody);
    }
}

As you can see, I am converting the entity I would like to save into Json string new post it to the server, if the respond is in success status, than read the database id and set it into my entity.

Great, now what about relationships? Here we go:

public async Task<int> CreateRelationship(long sourceDatabseID, 
    long targetDatabseID, string relationshipType)
{
    int retVal = -1;
    HttpClient httpClient = CreateHttpClient();

    string uri = "{\"to\":\"" + Your_Server_Name + "/db/data/node/" + 
        targetDatabseID + "\",\"type\":\"" + relationshipType+ "\";
    HttpContent stringContent = new StringContent(uri);
    HttpResponseMessage av = await httpClient.PostAsync("db/data/node/" + 
        sourceDatabseID + "/relationships", stringContent);

    if (av.IsSuccessStatusCode)
    {
        string responseBody = await av.Content.ReadAsStringAsync();
        retVal = GetIdFromRespond(responseBody);
    }
    return retVal;
}

I have created a method that gets two database ids of nodes and the type of the new relationship and again if the respond is in success status return the database id for the new relationship.

On the second part I will show how to read and retrieve data from Neo4j database and the really power of graph database will be shown. At the second part I will use the cypher query language so if you don’t know it, go read about it a bit.

Until next time, be happy.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

3 תגובות

  1. GraliaExhaura20 באפריל 2013 ב 18:44

    I'm generally to blogging and i genuinely appreciate your content. The write-up has really peaks my interest. I am going to bookmark your internet site and maintain checking for new data.

    [url=http://newchristianlouboutinb.webstarts.com/]new christian louboutin[/url]

    להגיב
  2. tietrinny2 במאי 2013 ב 14:02

    You made some decent points there. I looked on the web for the issue and found most people will go along with with your web-site.

    [URL=http://www.lululemononoutletsale.com/lululemon-tops.html]cheap lululemon[/URL]

    להגיב
  3. GraliaExhaura8 במאי 2013 ב 4:38

    I was quite pleased to find this web-site.I wanted to thanks for your time for this great read!! I undoubtedly enjoying each and every little bit of it and I've you bookmarked to take a look at new stuff you blog post.

    [URL=http://www.cheapformichaelkors.com/michael-kors-wallets-c-37.html]cheap michael kors handbags[/URL]

    להגיב