How to Retrieve Vertex IDs While Adding Vertices in a Transaction with JanusGraph.Net? #4407
-
I'm currently working on a project involving a graph database (JanusGraph), using the JanusGraph.Net library for operations. I'm facing an issue regarding transactions and vertex IDs retrieval. Here's a snippet of my code: var traversalSource = new GraphTraversalSource().WithRemote(connection);
var vertexTasks = new Dictionary<long, GraphTraversal<Vertex, Vertex>>();
var tx = traversalSource.Tx();
try
{
foreach (var item in DATA)
{
var addVertexTraversal = traversalSource.AddV("DATA").Property(Cardinality.Single, "ID", item.Key);
vertexTasks.Add(item_AidAnalyze.Key, addVertexTraversal);
}
tx.CommitAsync();
Console.WriteLine("Vertex added successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to add vertex: {ex.Message}");
tx.RollbackAsync();
} In this code, I'm adding vertices to the JanusGraph graph database within a transaction (tx). However, I also need to retrieve the IDs of these vertices for later use in adding properties and edges. Is there a way to achieve this within the context of a transaction? Without using transactions, I achieved my requirements with the following code: Vertex vertex_1 = g.AddV("DATA").Property(Cardinality.Single, "ID", item.Key).Next();
int id = vertex_1.id; But now I can only obtain |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You don't need to explicitly handle transactions here. You can simply construct a single traversal that creates your vertices and returns the IDs of the created vertices. JanusGraph Server will automatically execute such a traversal in its own transaction with automatic commit and rollback in case an exception occurs. This looks something like this in C#: var t = g.Inject(1); // Inject() is only necessary to get a `GraphTraversal`
foreach (var item in DATA)
{
t.AddV("DATA").Property(Cardinality.Single, "ID", item).Id().Aggregate("ids");
}
var ids = await t.Cap<List<object>>("ids").Promise(tr => tr.Next()); I used The important parts here are the |
Beta Was this translation helpful? Give feedback.
You don't need to explicitly handle transactions here. You can simply construct a single traversal that creates your vertices and returns the IDs of the created vertices. JanusGraph Server will automatically execute such a traversal in its own transaction with automatic commit and rollback in case an exception occurs.
This looks something like this in C#:
I used
async
here to execute the traversal, but you can of course also do it sy…