Thirumal
Thirumal

Reputation: 9676

How to access the vertex which is created using coalesce in gremlin?

How to access the vertex which is created using coalesce along with an edge in gremlin?

In the below query,

  1. when the country already exists, it return vertex to next step (adding state)
  2. returns new created edge, how to access the newly created vertex outside coalesce? I tried as() and select() but getting the error Edge cannot be cast to Vertex
g.V().hasLabel('country').has('name', 'Japan').fold()
        .coalesce(__.unfold(), __.addV('country').property('name', 'Japan')).as('country')
    //Adding state
    .coalesce(outE('has').inV().hasLabel('state').has('name', 'B'),
         __.addV('state').as('s').property('name', 'B').addE('has').from('country').select('s')).as('state')
    //Adding city/town
    .coalesce(outE('has').inV().hasLabel('city_town').has('name', 'F'),
             __.addV('city_town').property('name', 'F').addE('has').from('state')).as('city_town')

Upvotes: 1

Views: 50

Answers (1)

PrashantUpadhyay
PrashantUpadhyay

Reputation: 877

Here 2 child traversal within Coalesce are not returning same value.

1st child traversal i.e. outE('has').inV().hasLabel('state').has('name', 'B') returns a vertex.

2nd child traversal i.e. __.addV('state').property('name', 'B').addE('has').from('country') returns an edge.

So When the edge exists your query would return a vertex, however when the edge doesn't exists it will return an Edge. You could modify your query to give the same vertex in both the cases.

# First run creates the required entities. 
gremlin> g.V().
......1>   hasLabel('country').
......2>   has('name', 'Japan').
......3>   fold().
......4>   coalesce(__.unfold(), __.addV('country').property('name', 'Japan')).
......5>     as('country').
......6>   coalesce(
......7>     outE('has').inV().hasLabel('state').has('name', 'B'),
......8>     __.addV('state').
......9>     property('name', 'B').as('targetVertex').
.....10>     addE('has').from('country').
.....11>     select('targetVertex'))
==>v[2]

# Second run accesses the existing entities. 
gremlin> g.V().
......1>   hasLabel('country').
......2>   has('name', 'Japan').
......3>   fold().
......4>   coalesce(__.unfold(), __.addV('country').property('name', 'Japan')).
......5>     as('country').
......6>   coalesce(
......7>     outE('has').inV().hasLabel('state').has('name', 'B'),
......8>     __.addV('state').
......9>     property('name', 'B').as('targetVertex').
.....10>     addE('has').from('country').
.....11>     select('targetVertex'))
==>v[2]

Upvotes: 1

Related Questions