2

I having trouble finding the node that an node is in a relationship with. I want to be able to find the nodes with a relationship with selected node from the selected node.

Here is an example graph

Here is the code for the example graph:

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)

My attempt at getting the name of who Sarah likes:

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"

I was unable to find any way of getting the name of who likes Sarah without looking at the other nodes. Is this possible or am I wasting my time? Are there better ways to do any of this? Am I stuck with:

def get_who_likes_sarah():
    names = []
    for m in Man.select(graph):
        try:
            name = m.likes._related_objects[0][0].name
            if name == "Sarah":
                names.append(m.name)
        except:
            pass
    return names
James
  • 387
  • 1
  • 11

1 Answers1

0

You should get it by doing this:

for rel in graph.match(start_node=sarah, rel_type="LIKES"):
    names.append(rel.end_node()["name"])
Paulo Fabrício
  • 319
  • 3
  • 17