簡體   English   中英

py2neo在循環中添加關系

[英]py2neo adding relationships in a loop

我有以下代碼,該代碼從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']) 

我對您在這里想做什么感到有些困惑。 對於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})

我第二次嘗試,盡管現在它返回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']) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM