Zixi Wang
Zixi Wang

Reputation: 81

How to return true or false in gremlin

I want to compare the number of edges around a with a number and print true or false, something like this: g.V().out().count()==0 but == didn't work here, it always return false. Is there a alternative way?

Upvotes: 5

Views: 2084

Answers (2)

jbmusso
jbmusso

Reputation: 3456

You can simply chain .hasNext() to you Traversal, since it's an iterator.

Starting from a blank graph:

gremlin> graph = TinkerGraph.open()
==>tinkergraph[vertices: 0 edges:0]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices: 0 edges:0], standard]
gremlin> g.V().hasNext()
==>false

Let's add a single vertex

gremlin> g.addV('name', 'Alice')
==>v[0]
gremlin> g.V().out().hasNext()
==>false
gremlin> g.V().hasNext()
==>true

Upvotes: 1

Paul Jackson
Paul Jackson

Reputation: 2147

What is returned by the last count() step is a traversal, which provides an iterator interface that can be used to retrieve results.

If your goal is to count all the out edges of all the vertexes in the graph, return that single number, and compare that to 0, this will work:

gremlin> g.V().out().count().next()==0
==>false

If your goal is to do comparisons to 0 within the Gremlin language, the is() step can be used to test a number for equality:

gremlin> g.V().out().count().is(0)
==>v[2]
==>v[3]
==>v[5]

If you want to print the boolean results:

gremlin> g.V().choose(out().count().is(0), constant(true), constant(false))
==>false
==>true
==>true
==>false
==>true
==>false

Or maybe return maps with each vertex and its test result?

gremlin> g.V().as('a').choose(out().count().is(0), constant(true), constant(false)).as('b').select('a','b')
==>[a:v[1],b:false]
==>[a:v[2],b:true]
==>[a:v[3],b:true]
==>[a:v[4],b:false]
==>[a:v[5],b:true]
==>[a:v[6],b:false]

Upvotes: 5

Related Questions