Search code examples
graphgremlintinkerpopgremlinpython

Gremlin how to filter the results of a projection?


I have a query like this

g.V.has('id', 1).outE()
        .project('edge','vertex')
           .by(valueMap('number'))
           .by(inV().valueMap())

it returns a dictionary that looks like this: {"edge": { ...}, "vertex": { ..., "city": a value, ... }

I want to filter it based on a value of the inV() vertices. The vertices have a property called "city" and after I make the projection I want to filter out all the results where in the result the name of the city is not New York.

I tried

g.V().has('id', 1).outE()
        .project('edge','vertex')
           .by(valueMap('number'))
           .by(inV().valueMap())
.filter(select('vertex').select('city').is(eq("New York"))) 

but it doesn't return anything


Solution

  • I think you'd have a more readable and possibly better performing traversal if you chose to filter up front as in the answer PrashantUpadhyay supplied. If I could build upon that idea, I'd just offer that it would be better to get rid of the need to turn on path tracking by removing all the step labels and doing the filter this way:

    g.V().has('id', 1).outE().
      filter(inV().has('name','New York')).
      project('edge','vertex').
        by(valueMap('number')).
        by(inV().valueMap())
    

    If you absolutely must filter the resulting Map for some reason then:

    g.V().has('id', 1).outE().
      project('edge','vertex').
        by(valueMap('number')).
        by(inV().valueMap()).
      filter(select('vertex').select('city').unfold().is(eq("New York")))
    

    The issue is that valueMap() produces a List, so you have to unfold() that to evaluate the contents. I suppose you could have also done the unfold() in the valueMap() if you don't need the List in the result:

    g.V().has('id', 1).outE().
      project('edge','vertex').
        by(valueMap('number')).
        by(inV().valueMap().by(unfold())).
      filter(select('vertex').select('city').is(eq("New York")))