Getting vertices that are connected to ALL current

2020-05-09 19:05发布

问题:

I might be asking an obvious question, but new to the graphs and gremlin language and got a bit stuck.

I have a graph setup where I can find N vertices of a particular type. Let's say I find 2 vertices of type X. These vertices have edges to K vertices of type Y.

I want to find vertices of type Y that all have connection to the 3 vertices I found of the type X. In this situation, the vertices of type Y could be connected to either of the 3 vertices of type X, but I want to get only common ones.

Script to create sample data ```

g.addV("X1").property("name", "category1")
g.addV("X2").property("name", "category2")


g.addV("Y").property("name", "y1")
g.addV("Y").property("name", "y2")
g.addV("Y").property("name", "y3")


g.V().has("Y", "name", "y1").addE("isOf").to(g.V().has("X1", "name", "category1"))
g.V().has("Y", "name", "y1").addE("isOf").to(g.V().has("X2", "name", "category2"))

g.V().has("Y", "name", "y2").addE("isOf").to(g.V().has("X1", "name", "category1"))
g.V().has("Y", "name", "y2").addE("isOf").to(g.V().has("X2", "name", "category2"))

g.V().has("Y", "name", "y3").addE("isOf").to(g.V().has("X1", "name", "category1"))

```

And what I am interested finding are the "Y" vertices that have isOf category1 and category2, and potentially more categories. I need to eliminate vertices Y that connected only to a subset of specified categories.

回答1:

Aggregate all source vertices in a collection named x, then traverse to all y vertices and verify that each y vertex has n number of edges leading to vertices stored in x (where n equals the size of x).

gremlin> g.V().hasLabel("X1","X2").aggregate("x").
           in("isOf").dedup().
           filter(out("isOf").where(within("x")).count().
                  where(eq("x")).
                    by().
                    by(count(local))).
           valueMap()
==>[name:[y1]]
==>[name:[y2]]