【问题标题】:Update neo4j node with new relations, using py2neo使用 py2neo 使用新关系更新 neo4j 节点
【发布时间】:2015-04-24 04:54:08
【问题描述】:

我的代码添加了点头并创建了关系。当连接为 a->b、a->c、a->d 时它会更新,它可以工作(向节点添加新关系),但是当我添加连接 f->a 时,第二个名为 a 的节点是创建的。我怎样才能让它更新现有的节点a?

graph = Graph()
with open('test2') as fp:
    for line in fp:
        result = line.split('\t')
        category1 = graph.merge_one("Category", "name",result[0][result[0].rfind(':')+1:])
        category2 = graph.merge_one("Category", "name",result[1][result[1].rfind(':')+1:])
        print result[0][result[0].rfind(':')+1:] +"|"+result[1][result[1].rfind(':')+1:]
        graph.create_unique(Path(category1, "SubCategoryOf", category2))

我的测试文件是:

类别:Wars_involving_Burma 类别:Wars_by_country 类别:涉及战争的_缅甸 类别:Military_history_of_Burma 类别:Wars_involving_Burma 类别:Foreign_relations_of_Burma 类别:World_War_II 类别:涉及战争_保加利亚 类别:World_War_II 类别:Wars_involving_Burma

在这个例子中

类别:Wars_involving_Burma

被创建了两次。

【问题讨论】:

    标签: neo4j py2neo


    【解决方案1】:

    当我运行您的示例时,我没有两次获得节点。从您的问题中,我无法判断每行中有多少“类别:...”。从你如何分割线我认为它总是两条。一个可能的问题是您没有删除行尾,因此您的“Category:Wars_involving_Burma”节点之一可能在末尾有一个换行符。另外,您粘贴的是space,而不是\t

    这里是如何改进你的代码的建议,假设你的文件看起来像http://paste.ubuntu.com/10874106/

    graph = Graph()
    
    with open('test2') as fp:
        for line in fp:
            # strip the line ending first, then split by whitespace
            # I assume every line has to category entries?
            result = line.rstrip().split()
    
            # getting the category name is easier and more readable like this
            category1 = graph.merge_one("Category", "name", result[0].split(':')[1])
            category2 = graph.merge_one("Category", "name", result[1].split(':')[1])
    
            print result[0].split(':')[1] + '\t' + result[1].split(':')[1]
    
            # you don't need a Path here        
            graph.create_unique((category1, "SubCategoryOf", category2))
    

    此外,如果您希望您的“类别”节点是唯一的,您应该对“类别”节点的“名称”属性具有唯一性约束。

    密码:

    CREATE CONSTRAINT ON (n:Category) ASSERT n.name IS UNIQUE
    

    py2neo:

    graph.schema.create_uniqueness_constraint('Category', 'name')
    

    【讨论】:

    • 谢谢你,马丁。我已经发现问题是尾随的新行 (\n)。因此,虽然名称在数据库中看起来相同,但它是不同的。我将您的答案标记为正确,因为您建议的 rstrip() 会解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多