Howardyan
Howardyan

Reputation: 657

how to get a sub graph by using py2neo ogm

I know hot to get the sub-graph by using Cypher query. But since I use py2neo.ogm model. I just want to know how to get sub-graph by using ogm. for example:

class Company(GraphObject):
    __primarykey__ = "firm_name"

    firm_name = Property()

    shareHolder = RelatedFrom("Company", "hold_by")

I already created the relationship between companies. I want to get the sub-graph of a company. I checked the document of py2neo, seems there is no example... Anyone can help? Best regards

Upvotes: 0

Views: 776

Answers (1)

Portable
Portable

Reputation: 323

The source code (partly copied py2neo v3 ogm doc) produces the following movie titles list (not including the minus sign), when run with community edition of Neo4J with the movies sample (:play movies)

  • Something's Gotta Give
  • Johnny Mnemonic
  • The Replacements
  • The Matrix Reloaded
  • The Matrix Revolutions
  • The Matrix
  • The Devil's Advocate
  • A Few Good Men
  • Apollo 13
  • Frost/Nixon
  • A Few Good Men
  • Stand By Me
  • A Few Good Men
  • Top Gun
  • Jerry Maguire

    import py2neo
    import py2neo.ogm
    
    from py2neo import Graph, Node, Relationship
    from py2neo.ogm import GraphObject, Property, RelatedFrom, RelatedTo, RelatedObjects
    
    class Movie(GraphObject):
        __primarykey__ = "title"
    
        title = Property()
        tag_line = Property("tagline")
        released = Property()
    
        actors = RelatedFrom("Person", "ACTED_IN")
        directors = RelatedFrom("Person", "DIRECTED")
        producers = RelatedFrom("Person", "PRODUCED")
    
    
    class Person(GraphObject):
        __primarykey__ = "name"
    
        name = Property()
        born = Property()
    
        acted_in = RelatedTo(Movie)
        directed = RelatedTo(Movie)
        produced = RelatedTo(Movie)
    
    def authenticateAndConnect():
        # Authenticate the user using py2neo.authentication
        py2neo.authenticate('localhost:7474', '<username>', '<password>')
    
        # Connect to Graph and get the instance of graph
        return Graph('http://localhost:7474/default.graphdb/data/')     
    
    def foo():
        graph = authenticateAndConnect()
        for person in list(Person.select(graph).where("_.name =~ 'K.*'")):
            for movie in person.acted_in:
                print(movie.title)
    
    if __name__ == '__main__':
        foo()   
    

Upvotes: 3

Related Questions