from py2neo import Node, Relationship, Graph, NodeMatcher, RelationshipMatcher#导入我们需要的头文件 class Neo4jConn: head = None tail = None ''' # 连接neo4j 数据库 ''' def initConnect(self, host, port, username, password): graph = Graph('http://'+host+':'+port, auth=(username,password), name='neo4j') return graph ''' 向图数据库插入三元组 ''' def inserTriple(self, graph, head_type, head_name, relation_name, tail_type, tail_name): matcher = NodeMatcher(graph) if matcher.match(head_type, name=head_name).first() == None: node = Node(head_type, name=head_name) graph.create(node) self.head = matcher.match(head_type, name=head_name).first() else: self.head = matcher.match(head_type, name=head_name).first() if matcher.match(tail_type, name=tail_name).first() == None: node = Node(tail_type, name=tail_name) graph.create(node) self.tail = matcher.match(tail_type, name=tail_name).first() else: self.tail = matcher.match(tail_type, name=tail_name).first() self.inserRelation(graph, self.head, relation_name, self.tail) ''' 向图数据库创建节点 ''' def inserNode(self, graph, Node_type, Node_name): node = Node(Node_type, name=Node_name) return graph.create(node) ''' 向图数据库创建已存在的头节点与尾节点之间的关系 ''' def inserRelation(self, graph, head, relation_name, tail): relation = Relationship(head, relation_name, tail) return graph.create(relation) ''' 查找符合条件的实体 ''' def findNode(self, graph, node_type, node_name): matcher = NodeMatcher(graph) result = matcher.match(node_type, node_name).first() return result ''' 删除所有已有结点 ''' def deleteAll(self, graph): return graph.delete_all()