Search code examples
javagraph-databasesgremlintinkerpop3

Filtering Gremlin search by parent Vertex


I'm very new to Gremlin. I have been going through the documentation but continue to struggle to find an answer to my problem. I'm assuming the answer is easy, but have unfortunately become a little confused with all the different API options e.g. subgraphs, side effects and would like a little help/clarity from the expert group if possible.

Basically (as an example) I have a graph that looks like the below where I first need to select 'A' and then traverse down the children of 'A' only, to find if there is Vertex that matches 'A3' or 'A4'.

Selecting the first Vertex of course is easy, I simply do something like:

.V().has("name", "A")

However, I'm not sure how I can now isolate my second vertex search to the children of 'A' only. As I mentioned before I have stumbled upon subgraphs but have not being able to fully grasp how I can leverage this capability or if I should for my purpose.

I'm using TinkerPop3 and Java 8.

Any help will be greatly appreciated!

Example Graph


Solution

  • When you start your traversal with: g.V().has('name','A') you get the "A" vertex. Any additional steps that you add after that are restricted to that one vertex. Therefore g.V().has('name','A').out() can only ever give you the "A1" vertex and related children.

    To traverse through all the children of "A", you need repeat() step:

    g.V().has('name','A').
      repeat(out()).
        until(has('name',within('A3','A4'))
    

    So, basically find "A", then traverse through children until you run into "A3" or "A4".

    In the future, please consider supplying a Gremlin script that can be pasted into the console to construct your example graph - here's an example. An example graph in that form is quite helpful.