Search code examples
graph-databasesorientdb

Common vertex to two relationships in OrientDb


I am trying to pick up OrientDb and am trying out a few test queries to get a feel for the syntax and power of using graph databases. In particular I am having difficulty in find a common vertex satisfying two independent relationships to two other vertices that are unrelated.

For example,

Assuming I have a person vertex having attribute name, a car vertex having a model and a location vertex with attribute zip with the following edge dependencies

Person --- owns --> Car

Person --- lives --> Location

I am trying to find all the Person vertices that own a particular model of car and live at a particular zip.

I am not sure exactly what I am missing in my efforts, but any help would be greatly appreciated. Thanks


Solution

  • Let's assume this domain model:

    Car <--- Owns ---|   Person   |--- Lives ---> Location
    *   <--- Owns ---|1          *|--- Lives ---> 1
    

    All the persons who own a particular car model:

    select expand(in('Owns')) from Car where model = 'Volvo'
    

    All the persons who live at a particular zip:

    select expand(in('Lives')) from Location where zip = '10770'
    

    Let's combine the above to get all the persons who own a particular car model and live at a particular zip:

    select from (
        select expand(in('Owns')) from Car where model = 'Volvo'
    ) where out('Lives') contains (zip='10770')
    

    Minor:

    • The function expand() transforms the result set so as you get more than just the record IDs in the print out.
    • Passing Owns/Lives to the in/out functions ensures that only the edges of class types Owns/Lives are traversed.