py2neo 在循环中添加关系
我有一段代码,它从我的Neo4j数据库中获取一个域名列表,然后查找对应的IP地址,如果还没有建立关系,就创建一个关系。前面的部分运行得很好,但在最后几行代码创建关系时出现了错误。我确认列表里有两个项目——域名和IP,所以我不明白为什么会出错:
File "C:\Python26\beta7_whois4j_monitor_debug.py", line 63, in createrels
rels1 = graph_db.get_or_create_relationships((whoisnodes[0], "links", whoisnodes[1]))
IndexError: list index out of range
以下是代码:
whoisindex = graph_db.get_or_create_index(neo4j.Node, "whoisID")
domains = whoisindex.query("whoisID:*com")
for i in domains:
list1 = []
value1 = "{0}".format(i['whoisID'])
try:
e = socket.gethostbyname(value1)
except socket.gaierror:
e = 'exclude from list'
if e != 'exclude from list':
list1.append(value1)
list1.append(e)
for word in list1:
whoisnodes = []
whoisnodes.append(whoisindex.get_or_create("whoisID", word, "whoisID":word}))
rels1 = graph_db.get_or_create_relationships(
(whoisnodes[0], "links", whoisnodes[1]))
print "{0}".format(i['whoisID'])
2 个回答
0
这是我第二次尝试,不过现在它返回了一个JSON错误:
whoisindex = graph_db.get_or_create_index(neo4j.Node, "whoisID")
domains = whoisindex.query("whoisID:*com")
for i in domains:
list1 = []
value1 = "{0}".format(i['whoisID'])
try:
e = socket.gethostbyname(value1)
except socket.gaierror:
e = 'exclude from list'
if e != 'exclude from list':
list1.append(value1)
list1.append(e)
list1.append(whoisindex.get_or_create("whoisID", i, {"whoisID":i}))
rels1 = graph_db.get_or_create_relationships(
(list1[0], "links", list1[1]))
print "{0}".format(i['whoisID'])
0
我有点搞不清楚你想要做什么。在你这个循环 for word in list
的每一次迭代中,你都把 whoisnodes
重置为一个新列表,然后在下面的那一行才往里面添加一个项目。这就意味着在你调用 get_or_create_relationships
的时候,列表里最多只能有 一个 项目,所以当你试图访问 whoisnodes[1]
时,就会出现 IndexError
的错误。
你是不是想把 whoisnodes = []
放在循环外面呢?
顺便提一下,这里还有一个小错误(缺少大括号):
whoisindex.get_or_create("whoisID", word, "whoisID":word})
应该是:
whoisindex.get_or_create("whoisID", word, {"whoisID":word})