Question

With

batch = neo4j.WriteBatch(graph_db)
for n in nodes:
    batch.create_indexed_node_or_fail(index, key, value, {node properties})
batch.submit()

you can easily create indexed nodes in a batch.

But how can I create a node in a batch and add multiple key:value pairs at the same time? Or add the node to multiple indices?

One idea I thought of is to first create the nodes and then add them to the indices in a second batch:

for n in nodes:
    batch.create({node properties})
results = batch.submit()

for r in results:
    batch add node to index1
    batch add node to index2
batch.submit()

But this seems to complicated. Py2neo is so amazing, there must be an easier way.


Based on Nigel's answer, I tried to this for a list of nodes:

batch = neo4j.WriteBatch(graph_db)
item_in_batch = 0

for n in list_of_nodes:
    batch.create(n) # this works, all nodes are created
    batch.add_indexed_node("people", "key", "value from n", item_in_batch)
    batch.add_indexed_node("people", "key2", "other value from n", item_in_batch)
    i += 1
batch.submit()

Some nodes end up in my index, but not all. When I search the index for ('key:value-from-n") it returns a node but not the correct one. How can I access the 'internal' ID of the nodes when I try to add them to an index?


I tried the (currently testing) version 1.6.0 of py2neo and it works!

n = batch.create(node)

now returns a request object which can be used within the batch to refer to the node.

An example is in the docs for 1.6.0

Was it helpful?

Solution

You shouldn't need two batches. You should be able to create and add in the same batch. Something like:

batch = neo4j.WriteBatch(graph_db)
batch.create({"name": "Alice})
batch.add_indexed_node("people", "name", "Alice", 0)
batch.add_indexed_node("employees", "id", 2345678, 0)
batch.add_indexed_node("fighter_pilots", "call_sign", "Silver Eagle", 0)
batch.submit()

For unique indexing, you could use add_indexed_node_or_fail instead.

And thanks for the compliment :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top