Retrieve the Relationship object in Neomodel

1.4k Views Asked by At

I am using Neomodel and Python for my project. I have a number of nodes defined and am storing relevant information on the relationships between them. However I can't seem to find a mechanism for retrieving the relationship object itself to be able to use the attributes - I can only filter by the relationship attribute to return the Nodes.

class MyRelationship(StructuredRel):
    source = StringProperty()
    
class Person(StructuredNode):
    uid=UniqueIdProperty()
    first_name = StringProperty()
    last_name = StringProperty()
    
    people = RelationshipTo('Person', "PERSON_RELATIONSHIP", model = MyRelationship) 

I have a number of relationships of the same type [PERSON_RELATIONSHIP] between the same two nodes, but they differ by attribute. I want to be able to iterate through them and print out the to node and the attribute.

Given an Object person of type Person

for p in person.people: gives me the Person objects

person.people.relationship(p).source always gives me the value for the first relationship only

A Traversal also seems to give me the Person objects as well

The only way it seems to get a Relationship object is on .connect.

Any clues? Thanks.

2

There are 2 best solutions below

0
On

I just stumbled over the same problem and managed to solve it like below. But i am not sute if it is the most performant solution.

If you already have a Person node object in variable person:

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

Or iterating over all Person nodes:

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

I've checked the neomodel source code and there doesn't seem to be a way to achieve what you want in a more efficient way than what Roman said.

but you could always use cypher queries.

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

Then, now that you've stored all neighbors and the relationships between them, you can loop through them like so:

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

Hope this helps!

Ethan