All Collections
Data Analysis
Gremlin training
Gremlin Training 8: Basic Traversal - both()
Gremlin Training 8: Basic Traversal - both()

Learn to use the both()-step to find components which are reachable through incoming or outgoing references.

Kristine Marhilevica avatar
Written by Kristine Marhilevica
Updated over a week ago

Assume that we already have a Gremlin query which finds all components of type Person, with the name Nelson Bighetti:

g.V().has('Person', 'name', 'Nelson Bighetti')
component type

If we wish to find the components connected to the Nelson Bighetti component(s), without specifying the direction of the references, we can use the both()-step. When used with no parameters, it changes the current selection to all components which are connected to the current selection with an incoming or outgoing reference. The following query returns all components connected to the Nelson Bighetti component(s):

g.V().
has('Person', 'name', 'Nelson Bighetti').
both()
person component

If we want our search to only return components connected to our Nelson Bighetti component(s) through references of a specific type, this can be accomplished by passing the reference type we want to consider as a parameter to the both()-step. The following query finds all components connected to the Nelson Bighetti components through references of type Is Expert In:

g.V().
has('Person', 'name', 'Nelson Bighetti').
both('Is Expert In')
expert

It is also possible to pass multiple reference types to the both()-step if we want the search to traverse a specific set of references. The following query finds all components connected to the Nelson Bighetti components(s) through incoming or outgoing references of type Is Expert In or Owns:

g.V().
has('Person', 'name', 'Nelson Bighetti').
both('Is Expert In', 'Owns')

owns

Did this answer your question?