Search code examples
gremlinamazon-neptune

Find common recommendations in neptune db using gremlin queries


I have to find only common friends for two or more users in a way that both of them have same friend. g.V().has('users','id', within('A', 'B')).out('friend_with').values() This query will give back all friends that are associated with A or B. However, how can I get friends that are associated with A & B.

g.V().has('users','id', within('A', 'B')).out('friend_with').values()


Solution

  • One way to do this is to groupCount the results and only keep the ones where the count is 2. That means you will have got there from both A and B (assuming there are no duplicate edges between friends). This will look something like:

    g.V().has('users','id', within('A', 'B')).
      out('friend_with').
      groupCount()
    

    To then filter out anything that does not have a value of 2

    g.V().has('users','id', within('A', 'B')).
      out('friend_with').
      groupCount().
      unfold().
      where(select(values).is(2))
    

    and to get the values from the ones left

    g.V().has('users','id', within('A', 'B')).
      out('friend_with').
      groupCount().
      unfold().
      where(select(values).is(2)).
      select(keys).
      values()