neo4j 在Neomodel中检索关系对象

vwhgwdsa  于 2022-11-05  发布在  其他
关注(0)|答案(2)|浏览(189)

我在项目中使用了Neomodel和Python。我定义了许多节点,并存储了它们之间关系的相关信息。然而,我似乎找不到一种机制来检索关系对象本身,以便能够使用属性-我只能通过关系属性进行过滤,以返回节点。

class MyRelationship(StructuredRel):
    source = StringProperty()

class Person(StructuredNode):
    uid=UniqueIdProperty()
    first_name = StringProperty()
    last_name = StringProperty()

    people = RelationshipTo('Person', "PERSON_RELATIONSHIP", model = MyRelationship)

我在相同的两个节点之间有许多相同类型的关系[PERSON_RELATIONSHIP],但它们的属性不同。我希望能够遍历它们,并打印出to节点和属性。
给定Person类型的对象person
for p in person.people:提供了Person对象
person.people.relationship(p).source始终只为第一个关系提供值
Traversal似乎也给予了Person对象
它获得Relationship对象的唯一方法似乎是在.connect上。
有线索吗?谢谢。

iswrvxsc

iswrvxsc1#

我只是偶然发现了同样的问题,并设法解决了它,就像下面一样。但我不是苏特,如果它是最有表现的解决方案。
如果变量person中已经有一个Person节点对象:

for p in person.people:
    r = person.people.relationship(p)

或者在所有Person节点上迭代:

for person in Person.nodes.all():
    for p in person.people:
        r = person.people.relationship(p)
t9eec4r0

t9eec4r02#

我已经检查了neomodel的源代码,似乎没有一种方法可以比Roman所说的更有效地实现你想要的东西。
但您可以使用密码查询。

from neomodel import db
from models import Person, MyRelationship

john = Person.nodes.get(name='John')

results, cols = db.cypher_query(f"""MATCH (node)-[rel]-(neighbor)
                                    WHERE id(node)={john.id}
                                    RETURN node, rel, neighbor""")

rels = {}
neighbors = []

for row in results:
    neighbor = Person.inflate(row[cols.index('neighbor')])
    neighbors.append(neighbor)
    rel = MyRelationship.inflate(row[cols.index('rel')])
    rels[neighbor.id] = rel

然后,既然已经存储了所有邻居以及它们之间的关系,就可以像这样循环遍历它们:

for neighbor, rel in rels:
    print(f"john has a friendship with {neighbor} which has the source {rel.source}")

希望这对你有帮助!
伊森

相关问题