Although one of the most common use cases for demonstrating the capabilities of a graph database, I cannot seem to find a good example or best practice for obtaining "friends of friends" with OrientDB SQL.
Lets assume a social network and try to model it with "user" vertices and "is_friend_with" edges.
Definition:
Vertex class user with properties uuid (custom unique id) and name
Edge class is_friend_with with property status which can be "pending" or "approved"
Users are connected to each other with unidirectional edges. The direction doesn't really matter; as long as status="approved", those two users are friends.
This is one solution I came up with:
select from (
select expand($all) let
$a = (select expand(outE('is_friend_with')[status='approved'].inV('user').outE('is_friend_with')[status='approved'].inV('user')) from (select from user where uuid = '95920a96a60c4d40a8f70bde98ae1a24')),
$b = (select expand(outE('is_friend_with')[status='approved'].inV('user').inE('is_friend_with')[status='approved'].outV('user')) from (select from user where uuid = '95920a96a60c4d40a8f70bde98ae1a24')),
$c = (select expand(inE('is_friend_with')[status='approved'].outV('user').inE('is_friend_with')[status='approved'].outV('user')) from (select from user where uuid = '95920a96a60c4d40a8f70bde98ae1a24')),
$d = (select expand(inE('is_friend_with')[status='approved'].outV('user').outE('is_friend_with')[status='approved'].inV('user')) from (select from user where uuid = '95920a96a60c4d40a8f70bde98ae1a24')),
$all = unionall($a, $b, $c, $d)
) where uuid <> '95920a96a60c4d40a8f70bde98ae1a24'
(The user with uuid='95920a96a60c4d40a8f70bde98ae1a24' is the starting point.)
But, I don't find it very elegant. Some of the problems that I can spot immediately are:
- Repetition of
select from user where uuid = '95920a96a60c4d40a8f70bde98ae1a24'
. Unfortunately, I couldn't find a way to assign it to a variable and then use it in the "from" clause - I was forced to make all the combinations of incoming/outgoing edges/vertices instead of using both(), since I want to check every edge for
status="approved"
- This query also returns the direct friends, instead of friends of friends only
I tried to use traverse, but to no avail (again, didn't find a way how to check the edges for status="approved"
while traversing).
Could you, please, propose some OSQL solution for this problem? Thanks in advance.