Ali
Ali

Reputation: 1879

Get a list of common friends between more than 2 users in graph database

I am working with Titan graph database (v1.0), and I am looking for gremlin query to find the mutual friends between more than 2 users. Suppose I have a "user1", "user2", and "user3". I want to find the mutual friends between these 3 users. I know that the following query will give me the mutual friends between "user1" and "user2", but how can I find the mutual friends between more than 2 users? I know for two users I can use the following query:

g.V(user1).both("friend").where(both("friend").is(eq(user2)))

What about more than 2 users? I know I can do the same with all pairs, but this is not an efficient query!

Upvotes: 0

Views: 833

Answers (1)

Daniel Kuppitz
Daniel Kuppitz

Reputation: 10904

The match() step will probably be your best choice as it's the easiest to read and write. Might not be the fastest though.

g.V().has("name","user1").as("u1").
  V().has("name","user2").as("u2").
  V().has("name","user3").as("u3").
  match(
    __.as("u1").both("friend").as("f"),
    __.as("u2").both("friend").as("f"),
    __.as("u3").both("friend").as("f")
  ).where("f", neq("u1").and(neq("u2")).and(neq("u3"))).select("f")

Here's the query in action: http://www.gremlinbin.com/bin/view/570a30f9a58c9

Alternatively (without mid-traversal V()'s and without the where() conditions) you could do:

g.V().has("name","user1").both("friend").and(
    both("friend").has("name","user2"),
    both("friend").has("name","user3"))

Upvotes: 3

Related Questions