I'm brandnew to py2neo so I figured I would start off with a simple program. Its returning a TypeError: Index is not iterable. Anyway I'm trying to add a set of nodes and then create relationships for them while avoiding duplicates. Don't know what I'm doing wrong.
from py2neo import neo4j, cypher
graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")
happy = "happy"
glad = "glad"
mad = "mad"
irate = "irate"
love = "love"
wordindex = graph_db.get_or_create_index(neo4j.Node, "word")
for node in wordindex:
wordindex.add("word", node["word"], node)
def createnodes(a, b, c, d, e):
nodes = wordindex.get_or_create(
{"word": (a)},
{"word": (b)},
{"word": (c)},
{"word": (d)},
{"word": (e)},
)
def createrel(a, b, c, d, e):
rels = wordindex.get_or_create(
((a), "is", (b)),
((c), "is", (d)),
((e), "is", (a)),
)
createnodes(happy, glad, mad, irate, love)
createrel(happy, glad, mad, irate, love)
You have used a number of methods here incorrectly, beginning with the Index.add
method. This method should be used to add an existing node into an index but at this point in the code no nodes have actually been created. I think that you instead want to use Index.get_or_create
as follows:
nodes = []
for word in [happy, glad, mad, irate, love]:
# get or create an entry in wordindex and append it to the `nodes` list
nodes.append(wordindex.get_or_create("word", word, {"word": word}))
This essentially then replaces your createnodes
function as the nodes are created directly through the index, maintaining uniqueness.
You can then uniquely create your relationships with the node objects obtained by the code above, plus the GraphDatabaseService.get_or_create_relationships
method as follows:
graph_db.get_or_create_relationships(
(nodes[0], "is", nodes[1]),
(nodes[2], "is", nodes[3]),
(nodes[4], "is", nodes[0]),
)
Hope this helps
Nigel