neo4j,python,批量建立节点时,会重复建立相同名称节点。去重。

发布时间 2023-05-31 23:55:12作者: 又一岁荣枯

前提

经过度娘得知,可以使用第三方包去重,但只管去重,你后面关系乱了人家第三方包不管。=-=

或者

直接在neo4j里面使用数据库语言去重,但关系还是得重新建立。况且,我想用python去重。

干货来了

后来,我换了个思路,那么就是合并节点。(虽然跟去重差不多)
但总归总做出来了
使用NodeMatcher函数,注意3.5.4才推出的函数

解释一下思路
for循环录入节点关系
使用NodeMatcher判断是否重复
重复的情况下

直接建立关系(干货!)(新节点如何与旧节点建立关系)
就是 node一下旧节点的内容 但不提交!!!
直接新旧节点建立关系(记得提交新节点)

cong = Node(‘水利局’, name=data[i][1])
graph.create(cong)
zhu = Node(‘省份’, name=data[i][0])
zhucong = Relationship(cong,‘属于’,zhu)
graph.create(zhucong)

继续
不重复的情况下
建立新节点
又一轮新的if NodeMatcher判断水利局是否建立过

代码

def createMapping(contents,institutions):
    # 创建知识图谱节点
    graph = Graph('http://localhost:7474', user='neo4j', password='123456')
    graph.delete_all()  # 清除neo4j里面的所有数据
    # 确保相同名称的结点被视为同一个结点
    label_1 = '意见'
    label_2 = '解决部门'

    # 将每一个机构的关键词都与机构对应上
    for i in range(len(institutions)):
        # 将一个关键词去重
        keys[i] = list(set(keys[i]))
		# ===============================================
		# =====================去重关键代码==================================
        # 创建索引
        matcher = NodeMatcher(graph)
        nodelist = list(matcher.match(label_2,name=institutions[i]))
        # 已经有机构了
        if len(nodelist)>0:
            # 创建关键词节点
            for j in range(len(keys[i])):
                matcher = NodeMatcher(graph)
                nodelist = list(matcher.match(label_1,name=keys[i][j] ))
                if len(nodelist)>0:
                    print("已经有了")
                else:
                    node_1 = Node(label_1, name=keys[i][j])
                    graph.create(node_1)
                    node_2 = Node(label_2, name=institutions[i])
                    rel = Relationship(node_1, "请求", node_2)
                    graph.create(rel)

        else:
            # 创建机构节点
            node_2 = Node(label_2, name=institutions[i])
            graph.create(node_2)
            # 创建关键词节点
            for j in range(len(keys[i])):
                node_1 = Node(label_1, name=keys[i][j])
                graph.create(node_1)
                rel = Relationship(node_1,"请求",node_2)
                graph.create(rel)
    return