title: Optimizing gremlin query to avoid multiple traversals of graph
body: <p>I am little new to Gremlin query paradigm. I have following gremlin query to get all the nodes related to node of type <code>foo</code>.</p>
  <pre><code>g.V().hasLabel('foo').as('foo')
  .coalesce(out('hasBar'), constant('')).as('bar')
  .select('foo').coalesce(out('hasDelta'), constant('')).as('Delta')
  .select('foo').coalesce(out('hasBar').out('hasGamma'), constant('')).as('Gamma')
  .select('foo', 'bar', 'Delta', 'Gamma')
  </code></pre>
  <p>However this is not the optimized one as I have to traverse the graph multiple times and slows down the query execution.</p>
  <p><strong>Edit</strong></p>
  <p>Sample Data -</p>
  <pre><code>g.addV('foo').property('id', '1').property('p1', '1234').property('pk', 1)
  g.addV('bar').property('id', '2').property('p2', '12345').property('pk', 1)
  g.addV('Gamma').property('id', '3').property('p3', '123').property('pk', 1)
  g.addV('Delta').property('id', '4').property('p4', '12').property('pk', 1)
  g.V('1').addE(&quot;hasBar&quot;).to(g.V('2'))
  g.V('1').addE(&quot;hasGamma&quot;).to(g.V('3'))
  g.V('2').addE(&quot;hasDelta&quot;).to(g.V('4'))
  g.addV('foo').property('id', '5').property('p1', '12345').property('pk', 1)
  g.V('5').addE(&quot;hasBar&quot;).to(g.V('2'))
  g.V('5').addE(&quot;hasGamma&quot;).to(g.V('3'))
  g.addV('foo').property('id', '6').property('p1', '1').property('pk', 1)
  g.V('6').addE(&quot;hasBar&quot;).to(g.V('2'))
  g.V('6').addE(&quot;hasGamma&quot;).to(g.V('3'))
  g.addV('foo').property('id', '7').property('p1', '145').property('pk', 1)
  g.V('7').addE(&quot;hasBar&quot;).to(g.V('2'))
  g.V('7').addE(&quot;hasGamma&quot;).to(g.V('3'))
  g.addV('foo').property('id', '8').property('p1', '15').property('pk', 1)
  g.addV('bar').property('id', '9').property('p2', '78').property('pk', 1)
  g.addV('Gamma').property('id', '10').property('p3', '1236').property('pk', 1)
  g.addV('Delta').property('id', '11').property('p4', '1258').property('pk', 1)
  g.V('8').addE(&quot;hasBar&quot;).to(g.V('9'))
  g.V('8').addE(&quot;hasGamma&quot;).to(g.V('10'))
  g.V('10').addE(&quot;hasDelta&quot;).to(g.V('11'))
  </code></pre>
  <p>Previously I was fetching all foo and then was querying the corresponding bar, gamma and delta, which is very inefficient, so changed the query to fetch all at once, but now I am doing the same thing, but avoiding network calls.</p>
  <p>Above query gives following response -</p>
  <pre><code>[
  {
      foo: {},
      bar: {},
      Delta: {},
      Gamma: {}
  },
  {
      foo: {},
      bar: {},
      Delta: {},
      Gamma: {}
  }
  ]
  </code></pre>