Search in sources :

Example 51 with GraphTraversal

use of org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal in project janusgraph by JanusGraph.

the class JanusGraphIoRegistryTest method testGeoshapeAsGryo.

@Test
public void testGeoshapeAsGryo() throws SerializationException {
    Graph graph = EmptyGraph.instance();
    GraphTraversalSource g = graph.traversal();
    GraphTraversal[] traversals = { g.addV().property("loc", Geoshape.box(0.1d, 0.2d, 0.3d, 0.4d)), g.addV().property("loc", Geoshape.box(0.1f, 0.3f, 0.5f, 0.6f)), g.addV().property("loc", Geoshape.circle(0.1d, 0.3d, 0.3d)), g.addV().property("loc", Geoshape.circle(0.2f, 0.4f, 0.5f)), g.addV().property("loc", Geoshape.point(1.0d, 4.0d)), g.addV().property("loc", Geoshape.point(1.0f, 1.0f)) };
    serializationTest(traversals);
}
Also used : GraphTraversalSource(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource) Graph(org.apache.tinkerpop.gremlin.structure.Graph) EmptyGraph(org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) Test(org.junit.jupiter.api.Test)

Example 52 with GraphTraversal

use of org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal in project janusgraph by JanusGraph.

the class AdjacentVertexHasIdOptimizerStrategyTest method testAll.

@Test
public void testAll() {
    makeSampleGraph();
    // AdjacentVertexHasIdOptimizer out/in/both
    assertOptimization(g.V(sv[0]).outE("knows").has(ImplicitKey.ADJACENT_ID.name(), vs[50]).inV(), g.V(sv[0]).out("knows").hasId(vs[50]), optimizer);
    assertOptimization(g.V(sv[0]).inE("knows").has(ImplicitKey.ADJACENT_ID.name(), vs[50]).outV(), g.V(sv[0]).in("knows").hasId(vs[50]), optimizer);
    assertOptimization(g.V(sv[0]).bothE("knows").has(ImplicitKey.ADJACENT_ID.name(), vs[50]).otherV(), g.V(sv[0]).both("knows").hasId(vs[50]), optimizer);
    // AdjacentVertexHasIdOptimizer outE/inE/bothE
    assertOptimization(g.V(sv[0]).outE("knows").has(ImplicitKey.ADJACENT_ID.name(), vs[50]).inV(), g.V(sv[0]).outE("knows").inV().hasId(vs[50]), optimizer);
    assertOptimization(g.V(sv[0]).inE("knows").has(ImplicitKey.ADJACENT_ID.name(), vs[50]).outV(), g.V(sv[0]).inE("knows").outV().hasId(vs[50]), optimizer);
    assertOptimization(g.V(sv[0]).bothE("knows").has(ImplicitKey.ADJACENT_ID.name(), vs[50]).otherV(), g.V(sv[0]).bothE("knows").otherV().hasId(vs[50]), optimizer);
    // Result should stay the same
    assertSameResultWithOptimizations(g.V(sv[0]).as("v1").out("knows").hasId(vs[50].id()).as("v2").select("v1", "v2").by("id"), AdjacentVertexHasIdOptimizerStrategy.instance());
    // neq should not be optimized
    assertOptimization(g.V(sv[0]).in().hasId(P.neq(vs[50])), g.V(sv[0]).in().hasId(P.neq(vs[50])), optimizer);
    // repeat starts from vertex with id 0 and goes in to the sv[0] vertex then loops back out to the vertex with the next id
    int[] loop1 = { 0 };
    int[] loop2 = { 0 };
    GraphTraversal t1 = g.V(vs[0], vs[1], vs[2]).repeat(__.inE("knows").has(ImplicitKey.ADJACENT_ID.name(), sv[0].id()).outV().out(// TINKERPOP-2342
    "knows").sideEffect(e -> loop1[0] = e.loops()).has("id", loop1[0])).times(numV);
    GraphTraversal t2 = g.V(vs[0], vs[1], vs[2]).repeat(__.inE("knows").outV().hasId(sv[0].id()).out(// TINKERPOP-2342
    "knows").sideEffect(e -> loop2[0] = e.loops()).has("id", loop2[0])).times(numV);
    assertOptimization(t1, t2, optimizer);
}
Also used : Test(org.junit.jupiter.api.Test) JanusGraphAssert.assertSameResultWithOptimizations(org.janusgraph.testutil.JanusGraphAssert.assertSameResultWithOptimizations) AdjacentVertexHasIdOptimizerStrategy(org.janusgraph.graphdb.tinkerpop.optimize.strategy.AdjacentVertexHasIdOptimizerStrategy) ImplicitKey(org.janusgraph.graphdb.types.system.ImplicitKey) JanusGraphAssert.assertOptimization(org.janusgraph.testutil.JanusGraphAssert.assertOptimization) org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__) TraversalStrategy(org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) P(org.apache.tinkerpop.gremlin.process.traversal.P) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) Test(org.junit.jupiter.api.Test)

Example 53 with GraphTraversal

use of org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal in project open-kilda by telstra.

the class FermaMirrorGroupRepository method findFirstUnassignedGroupId.

@Override
public Optional<GroupId> findFirstUnassignedGroupId(SwitchId switchId, GroupId lowestGroupId, GroupId highestGroupId) {
    String switchIdAsStr = SwitchIdConverter.INSTANCE.toGraphProperty(switchId);
    Long lowestGroupIdAsLong = GroupIdConverter.INSTANCE.toGraphProperty(lowestGroupId);
    Long highestGroupIdAsLong = GroupIdConverter.INSTANCE.toGraphProperty(highestGroupId);
    try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V().hasLabel(MirrorGroupFrame.FRAME_LABEL).has(MirrorGroupFrame.SWITCH_ID_PROPERTY, switchIdAsStr).has(MirrorGroupFrame.GROUP_ID_PROPERTY, P.gte(lowestGroupIdAsLong)).has(MirrorGroupFrame.GROUP_ID_PROPERTY, P.lt(highestGroupIdAsLong)).values(MirrorGroupFrame.GROUP_ID_PROPERTY).order().math("_ + 1").as("a").where(__.not(__.V().hasLabel(MirrorGroupFrame.FRAME_LABEL).has(MirrorGroupFrame.SWITCH_ID_PROPERTY, switchIdAsStr).values(MirrorGroupFrame.GROUP_ID_PROPERTY).where(P.eq("a")))).select("a").limit(1)).getRawTraversal()) {
        if (traversal.hasNext()) {
            return traversal.tryNext().map(l -> ((Double) l).longValue()).map(GroupIdConverter.INSTANCE::toEntityAttribute);
        }
    } catch (Exception e) {
        throw new PersistenceException("Failed to traverse", e);
    }
    try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V().hasLabel(MirrorGroupFrame.FRAME_LABEL).has(MirrorGroupFrame.SWITCH_ID_PROPERTY, switchIdAsStr).has(MirrorGroupFrame.GROUP_ID_PROPERTY, lowestGroupIdAsLong)).getRawTraversal()) {
        if (!traversal.hasNext()) {
            return Optional.of(lowestGroupId);
        }
    } catch (Exception e) {
        throw new PersistenceException("Failed to traverse", e);
    }
    return Optional.empty();
}
Also used : GroupIdConverter(org.openkilda.persistence.ferma.frames.converters.GroupIdConverter) Collection(java.util.Collection) org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__) PersistenceException(org.openkilda.persistence.exceptions.PersistenceException) FermaPersistentImplementation(org.openkilda.persistence.ferma.FermaPersistentImplementation) SwitchIdConverter(org.openkilda.persistence.ferma.frames.converters.SwitchIdConverter) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) Collectors(java.util.stream.Collectors) MirrorGroupData(org.openkilda.model.MirrorGroup.MirrorGroupData) MirrorGroupRepository(org.openkilda.persistence.repositories.MirrorGroupRepository) List(java.util.List) SwitchId(org.openkilda.model.SwitchId) MirrorGroup(org.openkilda.model.MirrorGroup) MirrorGroupFrame(org.openkilda.persistence.ferma.frames.MirrorGroupFrame) Optional(java.util.Optional) FlowMeterFrame(org.openkilda.persistence.ferma.frames.FlowMeterFrame) KildaBaseVertexFrame(org.openkilda.persistence.ferma.frames.KildaBaseVertexFrame) GroupId(org.openkilda.model.GroupId) PathIdConverter(org.openkilda.persistence.ferma.frames.converters.PathIdConverter) PathId(org.openkilda.model.PathId) P(org.apache.tinkerpop.gremlin.process.traversal.P) PersistenceException(org.openkilda.persistence.exceptions.PersistenceException) PersistenceException(org.openkilda.persistence.exceptions.PersistenceException)

Example 54 with GraphTraversal

use of org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal in project open-kilda by telstra.

the class DatabaseSupportImpl method getPaths.

/**
 * Get all possible paths between source and destination switches.
 *
 * @param src source switch ID
 * @param dst destination switch ID
 * @return list of PathInfoData objects
 */
@Override
@SuppressWarnings("unchecked")
public List<PathInfoData> getPaths(SwitchId src, SwitchId dst) {
    return transactionManager.doInTransaction(() -> {
        FramedGraph framedGraph = getGraph();
        GraphTraversal<?, ?> rawTraversal = framedGraph.traverse(input -> input.V().hasLabel(SwitchFrame.FRAME_LABEL).has(SwitchFrame.SWITCH_ID_PROPERTY, src.toString()).repeat(__.outE(IslFrame.FRAME_LABEL).has(IslFrame.STATUS_PROPERTY, "active").inV().hasLabel(SwitchFrame.FRAME_LABEL).simplePath()).until(__.has(SwitchFrame.SWITCH_ID_PROPERTY, dst.toString()).or().loops().is(DEFAULT_DEPTH)).has(SwitchFrame.SWITCH_ID_PROPERTY, dst.toString()).path()).getRawTraversal();
        List<PathInfoData> deserializedResults = new ArrayList<>();
        while (rawTraversal.hasNext()) {
            ImmutablePath tpPath = (ImmutablePath) rawTraversal.next();
            List<PathNode> resultPath = new ArrayList<>();
            int seqId = 0;
            for (Object hop : tpPath) {
                if (hop instanceof Edge) {
                    Edge edge = (Edge) hop;
                    Vertex srcVertex = edge.outVertex();
                    resultPath.add(new PathNode(new SwitchId((String) srcVertex.property(SwitchFrame.SWITCH_ID_PROPERTY).value()), (Integer) edge.property(IslFrame.SRC_PORT_PROPERTY).value(), seqId++, (Long) edge.property(IslFrame.LATENCY_PROPERTY).value()));
                    Vertex dstVertex = edge.inVertex();
                    resultPath.add(new PathNode(new SwitchId((String) dstVertex.property(SwitchFrame.SWITCH_ID_PROPERTY).value()), (Integer) edge.property(IslFrame.DST_PORT_PROPERTY).value(), seqId++, (Long) edge.property(IslFrame.LATENCY_PROPERTY).value()));
                }
            }
            deserializedResults.add(new PathInfoData(0, resultPath));
        }
        return deserializedResults;
    });
}
Also used : FlowEvent(org.openkilda.model.history.FlowEvent) TransitVlanRepository(org.openkilda.persistence.repositories.TransitVlanRepository) FlowPath(org.openkilda.model.FlowPath) Isl(org.openkilda.testing.model.topology.TopologyDefinition.Isl) FlowEventRepository(org.openkilda.persistence.repositories.history.FlowEventRepository) Flow(org.openkilda.model.Flow) PersistenceContextManager(org.openkilda.persistence.context.PersistenceContextManager) FlowMeterRepository(org.openkilda.persistence.repositories.FlowMeterRepository) FlowRepository(org.openkilda.persistence.repositories.FlowRepository) SwitchFrame(org.openkilda.persistence.ferma.frames.SwitchFrame) SwitchConnectedDeviceRepository(org.openkilda.persistence.repositories.SwitchConnectedDeviceRepository) IslFrame(org.openkilda.persistence.ferma.frames.IslFrame) FlowPathRepository(org.openkilda.persistence.repositories.FlowPathRepository) FlowMirrorPoints(org.openkilda.model.FlowMirrorPoints) Collection(java.util.Collection) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) Instant(java.time.Instant) String.format(java.lang.String.format) List(java.util.List) Stream(java.util.stream.Stream) FramedGraph(com.syncleus.ferma.FramedGraph) Optional(java.util.Optional) SwitchRepository(org.openkilda.persistence.repositories.SwitchRepository) DetachedFactory(org.apache.tinkerpop.gremlin.structure.util.detached.DetachedFactory) TransactionManager(org.openkilda.persistence.tx.TransactionManager) FlowMeter(org.openkilda.model.FlowMeter) PathInfoData(org.openkilda.messaging.info.event.PathInfoData) ArrayList(java.util.ArrayList) DEFAULT_COST(org.openkilda.testing.Constants.DEFAULT_COST) OrientDbPersistenceImplementation(org.openkilda.persistence.orientdb.OrientDbPersistenceImplementation) IslRepository(org.openkilda.persistence.repositories.IslRepository) TransitVlan(org.openkilda.model.TransitVlan) PersistenceManager(org.openkilda.persistence.PersistenceManager) PathId(org.openkilda.model.PathId) OrientDbContextExtension(org.openkilda.persistence.orientdb.OrientDbContextExtension) Edge(org.apache.tinkerpop.gremlin.structure.Edge) Switch(org.openkilda.model.Switch) FlowMirrorPointsRepository(org.openkilda.persistence.repositories.FlowMirrorPointsRepository) PersistenceContext(org.openkilda.persistence.context.PersistenceContext) org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__) ImmutablePath(org.apache.tinkerpop.gremlin.process.traversal.step.util.ImmutablePath) PathNode(org.openkilda.messaging.info.event.PathNode) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) MeterId(org.openkilda.model.MeterId) RepositoryFactory(org.openkilda.persistence.repositories.RepositoryFactory) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) SwitchId(org.openkilda.model.SwitchId) SwitchStatus(org.openkilda.model.SwitchStatus) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) ArrayList(java.util.ArrayList) SwitchId(org.openkilda.model.SwitchId) PathNode(org.openkilda.messaging.info.event.PathNode) ImmutablePath(org.apache.tinkerpop.gremlin.process.traversal.step.util.ImmutablePath) PathInfoData(org.openkilda.messaging.info.event.PathInfoData) FramedGraph(com.syncleus.ferma.FramedGraph) Edge(org.apache.tinkerpop.gremlin.structure.Edge)

Example 55 with GraphTraversal

use of org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal in project sqlg by pietermartin.

the class TestGithub method test272.

@Test
public void test272() {
    this.sqlgGraph.addVertex("category", "a", "name", "hello");
    this.sqlgGraph.addVertex("category", "b", "name", "ignore");
    this.sqlgGraph.addVertex("category", "a", "name", "world");
    this.sqlgGraph.tx().commit();
    GraphTraversal gt = this.sqlgGraph.traversal().V().group().by("category").unfold().where(__.select(Column.values).count(Scope.local).is(P.gt(1))).select(Column.values).unfold().<String>values("name");
    printTraversalForm(gt);
    List<String> values = gt.toList();
    Assert.assertEquals(2, values.size());
    Assert.assertTrue(values.contains("hello"));
    Assert.assertTrue(values.contains("world"));
}
Also used : GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) BaseTest(org.umlg.sqlg.test.BaseTest) Test(org.junit.Test)

Aggregations

GraphTraversal (org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal)93 Vertex (org.apache.tinkerpop.gremlin.structure.Vertex)67 Test (org.junit.Test)57 List (java.util.List)51 TestGraphBuilder.newGraph (nl.knaw.huygens.timbuctoo.util.TestGraphBuilder.newGraph)50 VertexMatcher.likeVertex (nl.knaw.huygens.timbuctoo.util.VertexMatcher.likeVertex)44 Before (org.junit.Before)42 Matchers.containsInAnyOrder (org.hamcrest.Matchers.containsInAnyOrder)40 Matchers.contains (org.hamcrest.Matchers.contains)39 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)35 Lists (com.google.common.collect.Lists)34 FacetValue (nl.knaw.huygens.timbuctoo.search.FacetValue)31 Optional (java.util.Optional)24 P (org.apache.tinkerpop.gremlin.process.traversal.P)21 org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__ (org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__)20 ListFacetValue (nl.knaw.huygens.timbuctoo.server.mediatypes.v2.search.ListFacetValue)19 Matchers.is (org.hamcrest.Matchers.is)17 Mockito.mock (org.mockito.Mockito.mock)17 Matchers.empty (org.hamcrest.Matchers.empty)15 Edge (org.apache.tinkerpop.gremlin.structure.Edge)14