一、问题描述
在使用Neo4j构建知识图谱的时候,网上有非常多使用NodeMatcher或NodeMatch来获得相应的Node(实体),并且使用Relationship来建立Node(实体)之间的联系。如:
def __init__(self,url,username,password,data_path,sheet_name):
# 打开数据库
self.url = url
self.username = username
self.password = password
self.graph = Graph(self.url,auth = (self.username,self.password))
def Create_Relationship(self):
Nodes = NodeMatcher(self.graph)
url = 'D014024'
next_url = 'D005088'
Current_Node = Nodes.match(current_label,Unique_ID=url)
Next_Node = Nodes.match(next_label, Unique_ID=next_url)
Relation = Relationship(Current_Node,"link",Next_Node)
self.graph.create(Relation)
网上的解决方法如下:
1、增加first():
Current_Node = Nodes.match(current_label,Unique_ID=url).first()
Next_Node = Nodes.match(next_label, Unique_ID=next_url).first()
2、 修改筛选格式:
Current_url = "_.Unique_ID=" + "\"" + url + "\""
Current_Node = Nodes.match(current_label).where(Current_url)
Next_url = "_.Unique_ID=" + "\"" + next_url + "\""
Next_Node = Nodes.match(next_label).where(Next_url)
但是上述方法都没有办法解决问题。
二、问题解决
使用Run函数,借用Cypher语言创建Relation:
url = 'D014024'
next_url = 'D005088'
current_label = self.level_one + 'level' + str(i)
next_label = self.level_one + 'level' + str(i+1)
Relation = "MATCH (from:"+current_label+"{Unique_ID:"+"\""+url+"\""+"}),(to:"+next_label +"{Unique_ID:"+"\""+next_url+"\""+"}) MERGE (from)-[r:link]->(to)"
self.graph.run(Relation)
问题解决!