Search code examples
gremlintinkerpopjanusgraph

How to get properties hasid/key with vertexes info in one gremlin query or Gremlin.Net


I try to get properties which has key or id in following query by Gremlin.Net, but vertex info(id and label) in VertexProperty is null in result.

g.V().Properties<VertexProperty>().HasKey(somekey).Promise(p => p.ToList())

So i try another way, but it's return class is Path, and i had to write an ugly code for type conversion.

g.V().Properties<VertexProperty>().HasKey(somekey).Path().By(__.ValueMap<object, object>(true))

Is there a better way to achieve this requirement


Solution

  • I think basically the only thing missing to get what you want is the Project() step.

    In order to find all vertices that have a certain property key and then get their id, label, and then all information about that property, you can use this traversal:

    g.V().
        Has(someKey).
        Project<object>("vertexId", "vertexLabel", "property").
            By(T.Id).
            By(T.Label).
            By(__.Properties<object>(someKey).ElementMap<object>()).
        Promise(t => t.ToList());
    

    This returns a Dictionary where the keys are the arguments given to the Project step.

    If you instead want to filter by a certain property id instead of a property key, then you can do it in a very similar way:

    g.V().
        Where(__.Properties<object>().HasId(propertyId)).
        Project<object>("vertexId", "vertexLabel", "property").
            By(T.Id).
            By(T.Label).
            By(__.Properties<object>(someKey).ElementMap<object>()).
        Promise(t => t.ToList());
    

    This filters in both cases first the vertices to only have vertices that have the properties we are looking for. That way, we can use the Project() step afterwards to get the desired data back. ElementMap should give all information back about the properties that you want.

    Note however that these traversals will most likely require a full graph scan in JanusGraph, meaning that it has to iterate over all vertices in your graph. The reason is that these traversals cannot use an index which would make them much more efficient. So, for larger graphs, the traversals will probably not be feasible.

    If you had the vertex ids available instead of the property ids in the second traversal, then you could make the traversal a lot more efficient by replacing g.V().Where([...]) simply with g.V(id).