py2neo 2021.0.1 文档
https://pypi.org/project/py2neo/

  1. g = Graph('http://localhost:7474/',auth=("neo4j", "password"))

一键删除所有实体关系

  1. match (n) detach delete n

py2neo使用参考

https://www.icode9.com/content-4-867163.html

py2neo三元组导入器

  1. """
  2. py2neo导入器
  3. - 可识别已导入实体,避免出现同一标签下的 实体重复导入
  4. - 支持已pandas批量导入三元组数据
  5. - 关系导入修正,可识别已存在实体和自动新增缺损实体
  6. """
  7. class neo4jImportExe(object):
  8. """将txt中数据存入neo4j"""
  9. def __init__(self):
  10. # 定义neo4j对象
  11. self.g = Graph('http://localhost:7474/',name="neo4j",password="123456")
  12. # 创建实体函数
  13. def importNode(self,df,verbose=False):
  14. for index,row in df.iterrows():
  15. node = Node(row["label"],name=row["name"])
  16. node_matcher = NodeMatcher(self.g ).match(row["label"],name=row["name"]).first()
  17. if node_matcher is None:
  18. self.g .create(node)
  19. else:
  20. if verbose: print("结点",row["name"],"已存在")
  21. # 创建关系函数
  22. def importRelation(self,df,verbose=False):
  23. for index,row in tqdm(df.iterrows()):
  24. data1 = str(row["subjectname"])
  25. data2 = str(row["objectname"])
  26. label1 = str(row["subjectlabel"])
  27. label2 = str(row["objectlabel"])
  28. relation = row["relation"]
  29. node1 = Node(label1,name=data1)
  30. node2 = Node(label2,name=data2)
  31. node1_matcher = NodeMatcher(self.g ).match(label1,name=data1).first()
  32. node2_matcher = NodeMatcher(self.g ).match(label2,name=data2).first()
  33. if node1_matcher is None:
  34. self.g .create(node1)
  35. else:
  36. print("结点",data1,"已存在",end=" ")
  37. if node2_matcher is None:
  38. self.g .create(node2)
  39. else:
  40. print("结点",data2,"已存在",end=" ")
  41. # 重新获取结点
  42. get_node1_matcher = NodeMatcher(self.g ).match(label1, name=data1).first()
  43. get_node2_matcher = NodeMatcher(self.g ).match(label2, name=data2).first()
  44. re_matcher = RelationshipMatcher(self.g ).match((get_node1_matcher,get_node2_matcher),relation).first()
  45. if node1_matcher and node2_matcher and re_matcher is not None:
  46. print("关系",relation,"已存在")
  47. else:
  48. if node1_matcher is None or node2_matcher is None or re_matcher is None:
  49. rel = Relationship(get_node1_matcher,relation,get_node2_matcher)
  50. elif node2_matcher is None and node1_matcher is None:
  51. rel = Relationship(node1,relation,node2)
  52. self.g .create(rel)
  53. if verbose: print("创建新关系",data1,"--",relation,"--",data2)
  54. # 创建三元组
  55. def importTriple(self,df_data,verbose=True):
  56. pass