Search code examples
c#neo4jneo4j-driver

Neo4j Driver C# Unwind a list of objects


I'm looking how to unwind a list of objects (in memory) into Neo4j 4.0. Below is what I had previously using Neo4jClient nuget but I'm having to switch to Neo4j.Driver nuget instead.

Neo4jClient (old)

graphClient.Cypher
    .Unwind(towns, "tp")
    .Merge("t:Town {Name: tp.Id})")
    .OnCreate()
    .Set("t = tp")
    .ExecuteWithoutResults();

Neo4j Driver (done so far)

var session = driver.AsyncSession(o => o.WithDatabase("neo4j"));
        try
        {
            towns = towns.OrderBy(tt => tt.Id).ToList();
            foreach (var t in towns.Split(5000))
            {
                    Console.WriteLine($"Saving {t.Count:N0} of {town.Count:N0} Towns...");    
        **//STUCK HERE DOING UNWIND**  
            }
        }
        catch (Exception ex)
        {
            string error = $"ERROR (ADD TOWNS): {ex.ToString()}";           
            Console.WriteLine(error);
        }
        finally
        {
            await session.CloseAsync();
        }

Solution

  • Sadly the Neo4j Driver is pretty bare-bones - you need to build the Cypher query by hand, referring to parameters where required then pass those parameters into the query.

    var session = driver.AsyncSession(o => o.WithDatabase("neo4j"));
    try
    {
        towns = towns.OrderBy(tt => tt.Id).ToList();
        foreach (var t in towns.Split(5000))
        {
            Console.WriteLine($"Saving {t.Count:N0} of {town.Count:N0} Towns...");
    
            // Just return the town name - in your case, you'd MERGE or whatever, this is 
            // just an example
            var query = new Query("UNWIND {towns} AS town RETURN town", new Dictionary<string, object>
            {
                { "towns", towns }
            });
    
            var result = await session.RunAsync(query);
        }
    }
    catch (Exception ex)
    {
        string error = $"ERROR (ADD TOWNS): {ex.ToString()}";
        Console.WriteLine(error);
    }
    finally
    {
        await session.CloseAsync();
    }