Reputation: 129
Consider facebook search results of the people list scenario. I want to get all the people from the database (hasLabel('person')). For each of these people, I want to know whether the logged in person already have connected and follows. What is the best solution to get this in gremlin (possibly avoiding duplication)?
g.addV('person').property('id',1).as('1').
addV('person').property('id',2).as('2').
addV('person').property('id',3).as('3').
addV('person').property('id',4).as('4').
addE('connected').from('1').to('2').
addE('connected').from('2').to('3').
addE('connected').from('3').to('1').
addE('connected').from('4').to('2').
addE('follows').from('1').to('2').
addE('follows').from('1').to('3').
addE('follows').from('1').to('4').
addE('follows').from('2').to('1').
addE('follows').from('2').to('3').
addE('follows').from('3').to('1').
addE('follows').from('3').to('4').
addE('follows').from('4').to('2').
addE('follows').from('4').to('3').iterate()
For instance, if the logged-in person id is 2, the formatted JSON response will be
[
{
"id": 1,
"follows": true,
"connected": true
},
{
"id": 3,
"follows": true,
"connected": false
},
{
"id": 4,
"follows": false,
"connected": true
}
]
and if the logged-in person id is 4
[
{
"id": 1,
"follows": false,
"connected": false
},
{
"id": 2,
"follows": true,
"connected": true
},
{
"id": 3,
"follows": true,
"connected": false
}
]
Note: The JSON response is provided to understand the outcome, but I just wanted the Gremlin query to get the outcome.
Upvotes: 0
Views: 114
Reputation: 6341
Below is the general pattern you are looking for however based on the script you have listed above and the direction of the edges it's unclear exactly when to return true and when not to.
g.V().
hasLabel('person').
not(has('id', 2)). //find me person 2
project('id', 'follows', 'connected').
by('id').
by(
__.in('follows').
has('id', 2). //traverse all inbound follows edges to find if they go to person 2
fold(). //create an array (empty if nothing)
coalesce(unfold().constant(true), constant(false))). //return true if edge exists, else false
by(
__.out('connected').
has('id', 2).
fold().
coalesce(unfold().constant(true), constant(false)))
Based on the script you provided there is no way to get the answers you asked for. Let's look at just the connected
edges.
For vertex 2:
using in() we would get true
for 1 and 4 and false
for 3
using out() we would get true
for 3 and false
for 1 and 4
using both() all would be true
So based on the results above it looks like you want to use in()
edges. However when we apply that to vertex 4 all the results would be false
Upvotes: 1