neo4j_kg.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from py2neo import Node, Relationship, Graph, NodeMatcher, RelationshipMatcher#导入我们需要的头文件
  2. class Neo4jConn:
  3. head = None
  4. tail = None
  5. '''
  6. # 连接neo4j 数据库
  7. '''
  8. def initConnect(self, host, port, username, password):
  9. graph = Graph('http://'+host+':'+port, auth=(username,password), name='neo4j')
  10. return graph
  11. '''
  12. 向图数据库插入三元组
  13. '''
  14. def inserTriple(self, graph, head_type, head_name, relation_name, tail_type, tail_name):
  15. matcher = NodeMatcher(graph)
  16. if matcher.match(head_type, name=head_name).first() == None:
  17. node = Node(head_type, name=head_name)
  18. graph.create(node)
  19. self.head = matcher.match(head_type, name=head_name).first()
  20. else:
  21. self.head = matcher.match(head_type, name=head_name).first()
  22. if matcher.match(tail_type, name=tail_name).first() == None:
  23. node = Node(tail_type, name=tail_name)
  24. graph.create(node)
  25. self.tail = matcher.match(tail_type, name=tail_name).first()
  26. else:
  27. self.tail = matcher.match(tail_type, name=tail_name).first()
  28. self.inserRelation(graph, self.head, relation_name, self.tail)
  29. '''
  30. 向图数据库创建节点
  31. '''
  32. def inserNode(self, graph, Node_type, Node_name):
  33. node = Node(Node_type, name=Node_name)
  34. return graph.create(node)
  35. '''
  36. 向图数据库创建已存在的头节点与尾节点之间的关系
  37. '''
  38. def inserRelation(self, graph, head, relation_name, tail):
  39. relation = Relationship(head, relation_name, tail)
  40. return graph.create(relation)
  41. '''
  42. 查找符合条件的实体
  43. '''
  44. def findNode(self, graph, node_type, node_name):
  45. matcher = NodeMatcher(graph)
  46. result = matcher.match(node_type, node_name).first()
  47. return result
  48. '''
  49. 删除所有已有结点
  50. '''
  51. def deleteAll(self, graph):
  52. return graph.delete_all()