I have a graph structure like this-
Node1(Console) <----Uses--- Node2(Name, Age) -----plays----> Node3(Game)
So, i have three nodes -
Node1 is console like a PS3/ Nintendo.
Node2 is a person with properties name and Age.
Node3 is game node which holds game name like 'warcraft'.
Now I want to have a gremlin query which tells me that. How many users (Node2) who has the console like PS3, plays a game like 'warcraft'
I think i need to start the traverse from Node2 , filter it based on Node1 property i.e console as as 'PS3' and plays game like 'warcraft'
I am new to gremlin and using some thing like this -
g.V().hasLabel('user').outE('uses').inV().has('console', 'ps3').count()
the above query only answers half of my required result. How do i filter Node2 based on plays relationship as well.
Any help is appreciated.
There are multiple ways to write the query.
Option 1: Start from console
g.V().has('console', 'ps3').in('uses').where(out('plays').has('game', 'warcraft')).valueMap('name')
Let me explain the structure here:
g.V().has('console', 'ps3')
--> Select all vertices which have a property with key asconsole
and value asps3
in('uses')
--> From the set of previous vertices, jump to incoming vertices via an edge that has the labeluses
. At this stage, we would have player vertices in our solution.where(out('plays').has('game', 'warcraft'))
--> Apply a filter on existing solutions. Since we are usingwhere
we would not jump/traverse to the next step of vertices.valueMap('name')
--> Project one or more properties if existing solutions which are player vertices.Option 2: Another way to write above query
g.V().has('console', 'ps3').in('uses').as('myusers').out('plays').has('game', 'warcraft').select('myusers').by('name')
as('myusers')
--> Provides a reference/alias to the vertices at this stage. Note that it does not store all the results at this stage instead it just provides a reference to the type of vertices at this point in the query.out('plays').has('game', 'warcraft')
--> Unlike previous time when we did not jump since we were usingwhere
, this time we jump onto thegame
vertices.select('myusers').by('name')
--> since we want to project the users but the current solutions are game vertices, we need to select the user vertices which we do using the reference we stored earlier.Option 3: Start from user
g.V().hasLabel('user').where(out('plays').has('game','warcraft')).where(out('uses').has('console','ps3')).valueMap('name')
There are more ways to write this query such as using
path()
but I won't go into details here.Since you are beginning to learn Gremlin, I would recommend that you start with https://kelvinlawrence.net/book/Gremlin-Graph-Guide.html