在Java中按路径长度排序

时间:2015-03-17 10:55:56

标签: titan gremlin tinkerpop

我有类似下图的内容:

g = new TinkerGraph()
v1 = g.addVertex([name: 'one'])
v2 = g.addVertex([name: 'two'])
v3 = g.addVertex([name: 'three'])
v4 = g.addVertex([name: 'four'])
v5 = g.addVertex([name: 'five'])
v1.addEdge('contains', v2)
v2.addEdge('contains', v3)
v3.addEdge('contains', v4)
v4.addEdge('contains', v5)

现在我要删除v1及其所有“孩子”

v1.out('contains').loop(1){it.loops < 10}{true}.order{-it.a.path.toList().unique{a, b -> a <=> b}.size <=> it.b.path.toList().unique{a, b -> a <=> b}.size}.remove()
v1.remove()

(我必须从树叶中取出)

你能帮我把这个Groovy查询重写为Java吗?订单{...}部分存在问题。不确定如何从path获取Pair<Vertex, Vertex>

2 个答案:

答案 0 :(得分:3)

如果只需删除父节点及其所有子节点,则不确定顺序是否重要。我写了一个junit测试,我认为解决了你的问题。

import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.tg.TinkerGraph;
import org.junit.Assert;
import org.junit.Test;
import java.util.Iterator;

public class SOTest {

    private static final String EDGE_LABEL = "contains";

    @Test
    public void testSomething(){
        Graph g = new TinkerGraph();

        Vertex v1 = createVertex(g, "name", "one");
        Vertex v2 = createVertex(g, "name", "two");
        Vertex v3 = createVertex(g, "name", "three");
        Vertex v4 = createVertex(g, "name", "four");
        Vertex v5 = createVertex(g, "name", "five");

        v1.addEdge(EDGE_LABEL, v2);
        v2.addEdge(EDGE_LABEL, v3);
        v3.addEdge(EDGE_LABEL, v4);
        v4.addEdge(EDGE_LABEL, v5);

        removeParentAndChildren(v1);

        Assert.assertEquals(g.getVertices().iterator().hasNext(), false);

    }

    private static void removeParentAndChildren(Vertex vertex) {
        final Iterator<Vertex> vertexIterator = vertex.getVertices(Direction.OUT, EDGE_LABEL).iterator();
        if(vertexIterator.hasNext()) {
            vertex.getVertices(Direction.OUT, EDGE_LABEL).forEach(SOTest::removeParentAndChildren);
        }
        vertex.remove();
    }

    private Vertex createVertex(final Graph g, final String key, final String value) {
        Vertex v = g.addVertex(null);
        v.setProperty(key, value);
        return v;
    }

}

答案 1 :(得分:0)

我们最终使用了这个:

new HawkularPipeline<>(v1)
  .as("start")
  .out(contains)
  .loop("start", (x) -> true, (x) -> true)
  .toList()
  .forEach {
     c -> c.remove();
   }