Reputation: 87
I started to use Neo4j database some days ago and I end up with an issue I don't understand with the .NET driver. I have a code like this:
using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "neo4j")))
using (var session = driver.Session())
{
foreach(...)
{
// Build cypher query
string cypher_query = "...";
try
{
session.Run(cypher_query).Consume();
}
catch (Exception e)
{
Console.WriteLine("Failed running query : " + cypher_query + "\r\n" + e.Message);
}
}
}
I need to run a lots of cypher query (all are MERGE queries) within the foreach loop. My problem is that all queries failed after getting the first exception.
When I look what I display in the console, the cypher_query variable contains the correct thing and change at each iteration but the exception message remain always the same.
When I debug I have the feeling the query is correctly executed but we execute the catch clause anyway.
Any idea of what could happen here ?
Upvotes: 1
Views: 654
Reputation: 6270
I realise this is stale, but the reason is that the exception causes the session to go into an invalid state.
This code executes to show the problem, first a wrapper method:
public static void ExecuteCypher(IDriver driver, ISession session, string cypher, bool createNewSessionOnException = true)
{
try
{
//Attempt to run the cypher...
session.Run(cypher).Consume();
}
catch (Exception e)
{
//Write out error caught
Debug.WriteLine("Caught Exception: {0}", e.ToString());
//If we should create a new session
if (createNewSessionOnException)
{
//first clear up the old one
session.Dispose();
//Create new one
Console.WriteLine("New Session");
session = driver.Session();
}
}
}
Which you call like:
using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "neo4j")))
{
var session = driver.Session();
ExecuteCypher(driver, session, "Broken Cypher");
ExecuteCypher(driver, session, "Match (x) RETURN count(x)");
session.Dispose();
}
Which will work, but if you change it so it doesn't create a new session you'll get the exception:
using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "neo4j")))
{
var session = driver.Session();
ExecuteCypher(driver, session, "Broken Cypher", false); //<-- here
ExecuteCypher(driver, session, "Match (x) RETURN count(x)");
session.Dispose();
}
Upvotes: 1