check if value appears within list created from key() step in gremlin

658 Views Asked by At

I have a vertex that has a 'title' property. I have other vertices that have outgoing edges that have multiple properties. I'm trying to find vertices that have outgoing edges where the 'title' property value is a property key on the edge.

For example Vertex A has property {'title': ['lebron']} and Edge B has property {'lebron': 'basketball'}.

This is the example graph I have:

g.addV('person').property(id, 'bob')
g.addV('person').property(id, 'alice').addE().to(__.V('bob')).property('lebron', 'basketball')
g.addV('player').property('title', 'lebron').addE().from(__.V('bob'))

This is the query I currently came up with that isn't working:

   g
    .V('alice')
    .outE()
    .as('b')
    .otherV()
    .hasId('bob')
    .as('c')
    .select('b')
    .properties()
    .key()
    .fold()
    .as('k')
    .select('c')
    .outE()
    .otherV()
    .has('title', within('k')))
    .valueMap('title')
    .toList(); 
2

There are 2 best solutions below

1
On BEST ANSWER

Try this:

g
.V('alice')
.outE()
.as('b')
.otherV()
.hasId('bob')
.as('c')
.select('b')
.aggregate('keys').by(properties().key())
.select('c')
.out()
.where(values().where(within('keys')))
.valueMap('title')
.toList()
7
On

Here's likely a more "Gremlin-othic" approach. Gremlin is meant to be an imperative query language, so the best approach is to try to "find-then-filter". Instead of using as() and select() statements and jumping around everywhere, it is better to make your path/traversal, label things along the way, and then filter at the very end.

g.V('alice').outE('edge').as('b').inV().hasId('bob').out().
    where(eq('b')).
        by(values('title')).
        by(properties().key()).
    valueMap()

This approach uses the where()-by() pattern, which in this case takes two by() modulators. The first modulating the values coming into the where() statement (the vertices found by the last out()) and the second by() modulates what is inside of the where() statement (the property keys of the edge).

More on where()-by() here: https://kelvinlawrence.net/book/Gremlin-Graph-Guide.html#whereby