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

13 במרץ 2013

25 תגובות

In the first part I have talked about graph database in general and Neo4j in particular. I have covered the installation of Neo4j and the different ways to connected to it as a c# developer. We talked about the key elements in graph database: nodes and relationships, and how to create them in Neo4j graph database. If you haven't read the first part click here before you continue.

In order to use the full functionality of Neo4j you will need to learn to use cypher query language, it is quite simple and most of the code I will write in this post will use it.
Here is a small and helpful method I have created to execute cypher query on the Neo4j database and return the results from it:

private async Task<string> CypherQueryRunner(string query)
    string retVal = null;

    HttpClient httpClient = CreateHttpClient();
    HttpContent stringContent = new StringContent(query);

    HttpResponseMessage av = await httpClient.PostAsync
        ("db/data/cypher", stringContent);

    if (av.IsSuccessStatusCode)
        retVal = await av.Content.ReadAsStringAsync();

    return retVal;

This method is very simple, it gets a string contains cypher query and execute it on the Neo4j server, and return the results as string from the Neo4j server.

At the first post we learned how to create a node and how to create a relationship in Neo4j graph database, now I would like to retrieve data from my database and convert it back my entities and really use the power of the graph database.

Here is a method that reads entities from the database, after the code I will explain important elements in the method:

1. public async Task<List<Entity>> Read(List<int> nodeIds, 
2.    List<string> filterByLinkTypes , int depth = 1)
3. {
4.    List<Entity> retVal = null;
6.    var nodeIdsStr = BuildNodeIDString(nodeIds);
7.    var relationshipTypesFilterStr =  
8.       buildRelationshipTypesFilterStr(filterByLinkTypes);
9.    if (depth == 1)
10.    {
11.        var readQuery = "{  \"query\" : \"start n = node(" + 
12.             nodeIdsStr + ") return n\",  \"params\" : {  }}";
13.        var response = await CypherQueryRunner(readQuery);
15.        if (response != null)
16.        {
17.            retVal = CreateEntitiesFromDatabase(
18.              JsonConvert.DeserializeObject<Neo4jResults>(response));
19.        }
20.    }
21.    else
22.    {
23.        var readQuery = "{  \"query\" : \"start n = node(" + nodeIdsStr 
24.      +") match n-["+relationshipTypesFilterStr+"*1.." + depth + "]-m"
25.      +" WHERE m.NodeType!='Entity' return ID(m) \",\"params\" : { }}";
27.        var response = await CypherQueryRunner(readQuery);
28.        if (response != null)
29.        {
30.            var nodeIdsRespond = JsonConvert.DeserializeObject
31.                    <NodeIdsRespond>(response);
32.            nodeIds = GetNodeIdsFromNodeIdsRespond(nodeIdsRespond)
33.                    .Union(nodeIds).ToList<int>();
34.            retVal = await Read(nodeIds, filterByLinkTypes, 1);
35.        }
36.    }
38.    return retVal;
39. }


Lines 1 and 2 – the method gets a list of database node ids for retrieving, a list of string that represents the relationship types (family, friends…) and depth that represent whether I like to retrieve just the nodes on in the nodes id list or also the nodes connected to them until certain depth.

Line 6 – Build a string with the node ids (e.g. 1,2,7,8)

Lines 7 and 8 – Build a string of relationship types (e.g. friend, employ, x-girlfriend)

Lines 10-20 – this case we are handling the case of depth 1, meaning need to retrieve only the entities with ids in the input nodes id list – simple case, run an cypher query and deserialized back to objects.

Lines 23-25 In case the we need to retrieve entities with ids in the input nodes id list AND entities that have relationships to them (filtered by the input filterByLinkTypes), in this cypher query I am searching for those database node that fulfill the depth and relationship types according to the input from the initial node ids.

Line 32 and line 33 – get the results node ids from the Neo4j respond and union them with the input node ids list.

Line 34 – call this method again (yes recursion), combine nodeIds, initial filter types but now with the depth 1.

As you can see, of course we could have implemented this on a relational databases, but think what would happened if the depth will be 5, or 10 or even larger than 10. The performance in relational databases will be much (much!) bigger than the performance on a graph database and for those queries graph databases excel and this is the real power of graph databases.

What if you would like to update a node ? Very very easy using cypher:

public async Task Update(int nodeIndex, 
        Dictionary<string, string> keysAndValues)
    // A method that build the properties string 
    //(e.g. n.Name = 'Someone', n.Age = 35
    var updateStr = BuildUpdateString(keysAndValues);
    string updateQuery = "{  \"query\" : \"start n = node(" + 
        nodeIndex + ") SET " + updateStr + "  \",  \"params\" : {  }}";
    await CypherQueryRunner(updateQuery);

This method gets a database node index and a dictionary that represents the new properties of the node and using a simple cypher query update the node in the database.

And last operation in this example: delete, again very very simple let's look:

public async Task Delete(List<Entity> entities)
    // Build a string of node ids (e.g. 1,3,7)
    var NodeIDStr = BuildNodeIDString(entities);
    string updateQuery = "{  \"query\" : \"start n = node(" + NodeIDStr + 
        ") MATCH n-[r?]-() DELETE n, r;  \",  \"params\" : {  }}";
    await CypherQueryRunner(updateQuery);

This method get a list on database node ids and delete them from the database including all the relationship that they are a part of.

I hope you enjoyed and learned a bit about graph databases in general and Neo4j in particular. In those two blog posts I showed all the CRUD operations on neo4j database and how to work with cypher query language. There are more to learn but I Hope you realized the basics and understand the true power of a graph database.

Until next time, be happy.

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

כתיבת תגובה

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

25 תגובות

  1. TrauccusGeade14 באפריל 2013 ב 19:35

    Children's tooth development begins while the baby is in the womb. Teething usually occurs between the ages of six and nine months. Children usually have their full set of 20 primary teeth (milk teeth, baby teeth or deciduous teeth) by the age of three years. At about the age of six years, the first permanent teeth erupt (push through the gum).

  2. rooleatly22 באפריל 2013 ב 17:07

    you have an incredible blog here! would you like to make some invite posts on my weblog?

    [url=]red sole shoes[/url]

  3. Owercanna25 באפריל 2013 ב 2:26

    This web web page is really a walk-through for all of the information you wanted about this and didn't know who to ask. Glimpse here, and you will definitely discover it.

    [url=]red bottoms christian louboutin[/url]

  4. GraliaExhaura25 באפריל 2013 ב 8:18

    When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get 4 emails using the exact same comment. Is there any way you can actually get rid of me from that service? Thanks!

    [URL=]michael kors outlet orlando[/URL]

  5. tietrinny2 במאי 2013 ב 13:31

    Can I just say what a relief to uncover a person who truly knows what theyre talking about online. You absolutely know the best way to bring an concern to light and make it necessary. Alot more men and women need to read this and know this side of the story. I cant think youre not more common because you certainly have the gift.

    [url=]christian louboutin[/url]

  6. GraliaExhaura2 במאי 2013 ב 13:49

    This really answered my challenge, thank you!

    [URL=]michael kors backpack[/URL]

  7. nipreinee2 במאי 2013 ב 19:20

    Your location is valueble for me. Thanks!

    [url=]cheap christian louboutin shoes[/url]

  8. GraliaExhaura3 במאי 2013 ב 21:07

    Terrific Post.thanks for share..additional wait ..

    [URL=]michael kors backpack[/URL]

  9. peloEmegoHofe4 במאי 2013 ב 2:03

    There are some intriguing points in time in this article but I don't know if I see all of them center to heart. There is certainly some validity but I will take hold opinion until I appear into it further. Fantastic write-up , thanks and we want far more! Added to FeedBurner also

    [URL=]christian louboutin[/URL]

  10. iodidagak4 במאי 2013 ב 4:55

    Hello! I just would like to give an enormous thumbs up for the terrific information you have here on this post. I is going to be coming back to your weblog for a lot more soon.

    [URL=]lululemon yoga mat[/URL]

  11. GraliaExhaura4 במאי 2013 ב 5:49

    It is challenging to find knowledgeable persons on this topic, but you sound like you know what you're talking about! Thanks

    [URL=]michael kors canada[/URL]

  12. deecytheoft4 במאי 2013 ב 6:11

    The next time I read a blog, I hope that it doesnt disappoint me as significantly as this one. I mean, I know it was my choice to read, but I essentially thought youd have something intriguing to say. All I hear is usually a bunch of whining about some thing which you could fix if you werent too busy seeking for attention.

    [URL=]red bottom shoes[/URL]

  13. tietrinny8 במאי 2013 ב 17:53

    You made some decent points there. I looked online for the problem and located most individuals will go together with along with your webpage.

    [URL=]lululemon annapolis[/URL]

  14. GraliaExhaura8 במאי 2013 ב 23:32

    I'd have to check with you here. Which just isn't something I commonly do! I enjoy reading a post that can make consumers feel. Also, thanks for allowing me to comment!

    [URL=]mikael kors[/URL]

  15. peloEmegoHofe9 במאי 2013 ב 0:04

    This internet internet site is actually a walk-through for all the info you wanted about this and didn't know who to ask. Glimpse here, and you will certainly discover it.

    [URL=]christian louboutin[/URL]

  16. rooleatly9 במאי 2013 ב 0:32

    This will be the proper weblog for any person who desires to discover about this subject. You recognize so considerably its practically hard to argue with you (not that I really would want?-HaHa). You certainly put a new spin on a subject thats been written about for years. Awesome stuff, just excellent!

    [URL=]lululemon shorts[/URL]

  17. nipreinee9 במאי 2013 ב 2:58

    This internet web page is certainly a walk-through for all of the information you wanted about this and didn't know who to ask. Glimpse here, and you will undoubtedly discover it.

    [url=]red bottoms christian louboutin[/url]

  18. GraliaExhaura9 במאי 2013 ב 15:02

    you might have a fantastic blog here! would you like to make some invite posts on my weblog?

    [URL=]michael kors gansevoort[/URL]

  19. iodidagak15 במאי 2013 ב 18:05

    This internet webpage is definitely a walk-through for all the info you wanted about this and didn't know who to ask. Glimpse here, and you'll definitely discover it.

    [URL=]lululemon scuba hoodie[/URL]

  20. joxBloopy21 במאי 2013 ב 16:37

    As good as every legacy and new-look IT vendor has its own plagiarize on making the uninterrupted data center more programmable via software and less dependent on specialized, proprietary and pricey hardware.

  21. margertcassels2115 בספטמבר 2013 ב 23:19

    and also sufficiently fortunate to to fit for the reason that nations a femeale for example along with in job for individuals a good [url=]replica oakley sunglasses[/url]
    hello kitten sunglasses cheap oaklat they sale nfl colorings wholesale shades refurbishment oaklat they angell hat clearance rfin3460 aviator even even large tinted glasses asia ray ban 54017 ray ban rc3026 aviatnot, wedding rings frameproperly brown lens fake oakley sunglasses inexpensive discount solar shades gucci form cheap galaxy good snapturn back snapfor your family weed
    is a great hat usually are challenging for supply you with a unique key large an awesome with ! are usually in members of the squad activities a top quality backside look-alike athletics , which includes far more who are sun after dark cheap locaste glasses replica hug you ban 41ninety four oakley locs eyewear from suppliers goblets window frames women Ni yankeefarreneheit ruddy Blue 9 fifty Snapback cheap oakleys with free shipping irvine fitted caps

    Related help links:[url=]Online shopping Oakley Active Sunglasses on summer, with low price in high quality on all orders are your best choice.[/url]

  22. cttqjrhsmz@gmail.com24 באוקטובר 2013 ב 8:57

    1、寝室卧谈会。室友A:“有些人真傻,愿意为女朋友献出生命,换作是我,至多只愿意献自己的手。”B:“那是啊,等你有了女朋友,你就不需要自己的手了。”2、有天A逃课在宿舍睡觉,给在上课的B发短信:点名没?答:点了,没帮你点,哈哈哈。一会儿, A回复:刚刚查宿舍,我爬到了你床上。3、晚上寝室无聊讨论到关于舌吻的话题 。上铺哥们忽然问舌吻是现代才有的吗?古代人会这招吗?正当大家为这个高深的问题陷入沉思时,宿舍最闷骚的那位幽幽的来了句:“诸葛亮舌战群儒~~~”4、工科男,班级有七个女生!一次和其它班同学一起吃饭!一哥们问我说:听说你们班有七仙女?我一仰头一杯酒入喉后,回了句,”那TM哪是七仙女,简直是江南七怪!”生活囧事让人憋不住想笑

  23. lvygbnmvzhd@gmail.com30 באוקטובר 2013 ב 21:25