我有一个非常简单的示例图,我正在尝试对其进行深度优先查询。假设图形边缘如下所示
A->B
A->C
B->D
B->E
C->F
C->G
从 A 开始的深度优先搜索应该返回
A-B-D-E-C-F-G
但是如果我能得到下面的订单那就更好了
D-E-B-A-F-G-C-A
如何创建将输出此订单的 Gremlin 查询?如果我做这样的事情
g.V('A').repeat(outE().inV()).emit()
我得到的顺序是 A、B、C、D、E、F、G,即广度优先。我不知道如何获得上面我想要的订单。
最佳答案
为了让其他人重现,这里是示例图:
g = TinkerGraph.open().traversal()
g.addV().property(id, 'A').
addV().property(id, 'B').
addV().property(id, 'C').
addV().property(id, 'D').
addV().property(id, 'E').
addV().property(id, 'F').
addV().property(id, 'G').
addE('link').from(V('A')).to(V('B')).
addE('link').from(V('A')).to(V('C')).
addE('link').from(V('B')).to(V('D')).
addE('link').from(V('B')).to(V('E')).
addE('link').from(V('C')).to(V('F')).
addE('link').from(V('C')).to(V('G')).iterate()
A depth first search from A should return
A-B-D-E-C-F-G
gremlin> g.V('A').repeat(out('link')).until(__.not(outE('link'))).path().
unfold().dedup().id().fold()
==>[A,B,D,E,C,F,G]
But if I could get the below order it would be even better
D-E-B-F-G-C-A
这个有点从后面卷起路径。这很棘手,但可行:
gremlin> g.V('A').
repeat(outE('link').aggregate('edges').inV()).
until(__.not(outE('link'))).
flatMap(
union(identity(),
repeat(inE('link').where(within('edges')).as('current').
map(select('edges').unfold().
where(neq('current').and(without('done'))).
outV().where(without('ad')).fold()).as('bl').
select(last, 'current').store('done').
filter(outV().where(without('bl').and(without('ad')))).
outV().store('ad')).
emit())).
id().fold()
==>[D,E,B,F,G,C,A]
但是,获取路径并在应用程序端进行排序可能要容易得多。
关于gremlin - Tinkerpop Gremlin 深度优先搜索顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47013872/