Search code examples
graph-databasesgremlintinkerpoptinkerpop3janusgraph

Gremlin querying with the depth information while traversing


I have a use-case where users are in a hierarchy like

user1 --HAS_CHILD--> user2--HAS_CHILD--> user3 --HAS_CHILD--> user4

For the given user I need to get all the cars owned by that user and all the cars owned by the children of that user. With the cars, I need to have the user(owner) as well as the depth of that user from the given user.

Ex. The given user is user2, then user3 has depth 1, user4 has depth 2.

I can get the car details and owner information using the following query but how can I get the childDepth ?.

g.V().has("User", "id", "user2")
 .union(
    __.out("OWNS").hasLabel("Car"),
    __.repeat(
       __.out("HAS_CHILD").hasLabel("User")
    ).emit().out("OWNS").hasLabel("Car")
 )
 .project("plateNumber", "owner", "model", "year", "childDepth")
 .by(__.values("plateNumber").fold())
 .by(__.in("OWNS").values("owner").fold())
 .by(__.values("model").fold())
 .by(__.values("year").fold())
 .by(???)

Solution

  • You can use withSack:

    g.withSack(0).V().has("User", "id", "user2")
     .union(
        __.out("OWNS").hasLabel("Car"),
        __.repeat(
             __.sack(sum).by(constant(1))
           .out("HAS_CHILD").hasLabel("User")
        ).emit().out("OWNS").hasLabel("Car")
     )
     .project("plateNumber", "owner", "model", "year", "childDepth")
     .by(__.values("plateNumber").fold())
     .by(__.in("OWNS").values("owner").fold())
     .by(__.values("model").fold())
     .by(__.values("year").fold())
     .by(__.sack())