Search code examples
databasegraphgremlingraph-databases

Gremlin query to find values of vertices which are common between 2 different vertices


I am trying to write a query to find common vertices between 2 given vertices.

2 types of vertices: User and City

2 types of edges: friend_of, lives_in

  • User_1 is friend_of user_2 and user_3
  • user_2 lives in chennai
  • user_3 lives in delhi

I am trying to write a query to "find all users who are friend of user_1 and lives in chennai".

g.V('user_1').out('friend_of').out('lives_in').has('id', 'chennai').values('id')

I cound understand that this query has traversed to the city nodes. So i will endup getting the city names. I need a way to traverse till the user nodes and just query the city nodes and filter.

follow up question: How can i traverse one level next. Like "who are user_1's friends and friends of friends who lives in Chennai.

Note: Please ignore the schema. city could also be an attribute to user, but this is just an example for the problem i am looking at.

Thanks in advance.


Solution

  • You should be able to do something like this. Without sample data I have not been able to test it.

    g.V('user_1').
      out('friend_of').
      where(out('lives_in').has('id', 'chennai')).
      values('id')
    

    For the second question, friends of friends living in Chennai

    g.V('user_1').as('me').
      out('friend_of').
      in('friend_of).
      where(neq('me')).
      where(out('lives_in).has('id', 'chennai')).
      values('id')