Setting up Neo4j to work with a C#.Net project

Just a quick guideline to refresh my mind:

Installing Neo4j Server

First, go to their website and download and install the latest version. If you are planning to use this installation for dev purposes only, you don’t need the enterprise version, the individual works just fine.

Installing it should take no time and be quite simple, but once it’s done, run the program and click on Start to start the server, then click on the link to browse to it.

Unless you edit the config file to set off the authentication it will ask you to login, the default user/pass was something like neo4j/neo4j or neo4j/admin, I can’t remember right now. Once that’s done it asks to change the default password to a new one, you can set your own password here.

Update Jan 2018

There is no wizard installer now and you must download a zip, extract it, and then run “bin/neo4j install-service” from the main directory (the one above bin) using cmd. Then run “bin\neo4j start” to start it.

Now everything is ready to start connecting to it from .Net and add nodes into the database.

Setting up Visual Studio

In your .Net project you need to install these NuGet packages: Neo4jClient by Readyfy and Neo4jClient.Extension by Simon Pinn. These will allow you to access the required libraries.

Now you can just code something like this to create a client object that connects to the database:

using Neo4jClient;

public GraphClient GetClient()
{
var client = new GraphClient(new Uri("http://127.0.0.1:7474/db/data"), "neo4j_username", "yourPassword");
client.Connect();
return client;
}

If you are using your local connection that should do. Take care the URL to access the database to modify the data is different than the one used to browse it (http://127.0.0.1:7474/browser/).

Remember! For the connection to work Neo4j must be running, make sure you started it and its running if it doesn’t connect.

Creating the first node

Simple example:

var properties = new Dictionary<string, object>
{
{ "CompanyId", 1 },
{ "Prop2", "someValue" },
{ "Prop3", 5 }
};

var statement = _client.Cypher
.Merge("(x:Company { CompanyId: {companyId} })")
.OnCreate().Set("x = {x}")
.OnMatch().Set("x = {x}")
.WithParams(new
{
companyId = 1,
x = properties
});

await statement.ExecuteWithoutResultsAsync();

We are creating a statement that does an insert or update, we use Merge() for that and then define what to do in case of creation (OnCreate) or update (OnMatch). In here, we are basically replacing the entire object (defined by an x) with what comes in the param {x}. Notice there are basically two params, the companyId which I’m hardcoding to 1 just for tutorial purposes and the x which is a Dictionary with the node properties and their values. Also notice I’m referencing the params with the brackets, while the node is defined without brackets, that’s how the two x variables are differentiated.

Remember! The Cypher is case sensitive and what’s written in C# code must match what’s written in the strings, so that x you see there, it can’t be X or y, it must stay exactly as it is defined in the clause.

Remember! Neo4j automatically adds an <id> to all nodes and relationships, to avoid misunderstandings it can be useful to avoid giving a node an id parameter and instead call it nodeId or something like companyId.

Creating the first relationship

Well, there’s no point on having a graph DB without relationships, so here’s a basic example on how to add one:

var node = new Company(); // just imagine this is filled with data.
var continent = new Continent() // Same
var key = $"Company({node.CompanyId})-Continent({continent.ContinentId})"; //Just a way for me to give this relationship a uniquekey.

var addStatement = _client.Cypher
.Match($"(left:Company)", "(right:Continent)")
.Where((Company left) => left.CompanyId == node.CompanyId)
.AndWhere((Continent right) => right.continentId == continent.ContinentId)
.Merge("(left)-[x:InRegionOf { key: '" + key + "'}]-(right)")
.OnCreate().Set("x = {x}")
.OnMatch().Set("x = {x}")
.WithParams(new { x = new { key } });

await addStatement.ExecuteWithoutResultsAsync();

To create a relationship we first need to have the nodes added to the database, then we select them and create a relationship between them. In here, we use Match to set what type of nodes we are planning to retrieve, we can actually use Match to set an id clause and already get the exact node without the Wheres, but in case you need a little bit more of complexity on determining the node I though this example helps more.

Once we have selected the right nodes we do a Merge like before to insert/update the relationship between them. Also, I’m giving these relationships a key to identify them so I can point/remove them later, but you don’t need to do that. If you want to give the relationships some properties though, this is where you should do so (like before).

Remember! Again, Cypher is case sensitive and what’s written in C# code must match what’s written in the strings, so that left variable you see there, must be defined as left in the C# side or it won’t work. Be careful because C# won’t notice the issue and will compile without trouble until the code is executed and crashes. If you define a node as left, then it must be exactly like that on the C# codes.