Search code examples
gremlintinkerpop

Conditional has()


I am building a query based on passed parameters. For example, if pass p1='a' and p2='b', my query will look something like this:

g.V()
  .has("p1","a")
  .has("p2","b")

If let's say p2 is not passed, then I won't have a second check:

g.V()
  .has("p1","a")

Is it possible to perform parameter check inside the query instead of creating conditional checks for parameters before creating query?

Edit: Use case is based RESTful web service where I have something like, /server/myEndpoint?p1=a and endpoint implementation would build gremlin query with .has() steps solely based on presence of p1 or p2, so if p2 is not passed, query would look like in second snippet, and if passed would look like the one in first.


Solution

  • One possible approach is to build GraphTraversal until it's not executed:

            Map<String, String> map = new HashMap<>();
            map.put("p1", "a");
            map.put("p2", null);
    
            final GraphTraversal<Vertex, Vertex> v = g.V();
    
            map.forEach((k,v) -> {
                if(v != null) {
                    v.has(k,v);
                }
            });
    
            return v.toStream().collect(Collectors.toList());