py2neo:从没有密码的关系和所有传入关系中获取结束节点

时间:2017-03-31 21:18:35

标签: python-3.x neo4j py2neo

我无法找到节点与之关系的节点。 我希望能够从所选节点中找到与所选节点有关系的节点。

Here is an example graph

以下是示例图的代码:

ActiveCell

我试图获得莎拉喜欢的名字:

from py2neo import Node, Relationship, Graph, NodeSelector, Path
from py2neo.ogm import *
graph = Graph(user = 'neo4j', password = 'neo4j')
graph.delete_all()

class Man(GraphObject):
    __primarykey__ = "name"
    name = Property("name")
    likes = RelatedTo("Woman", "LIKES")

class Woman(GraphObject):
    __primarykey__ = "name"
    name = Property("name")
    likes = RelatedTo("Man", "LIKES")

new_man = Man()
new_man.name = "John"
graph.push(new_man)

new_woman = Woman()
new_woman.name = "Sarah"
new_woman.likes.add(Man.select(graph, primary_value="John").first())
graph.push(new_woman)

new_man = Man()
new_man.name = "Joe"
new_man.likes.add(Woman.select(graph, primary_value="Sarah").first())
graph.push(new_man)

在没有查看其他节点的情况下,我无法找到任何方式获取Sarah的名字。这可能还是我在浪费时间?有没有更好的方法来做这些? 我坚持:

sarah = Woman.select(graph, primary_value="Sarah").first()
sarah.likes._related_objects[0][0].name
# returns "John"
# or
list(sarah.__ogm__.related.values())[0]._related_objects[0][0].name
# returns "John"

1 个答案:

答案 0 :(得分:0)

你应该这样做:

for rel in graph.match(start_node=sarah, rel_type="LIKES"):
    names.append(rel.end_node()["name"])