org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExportSpecification.java    From amazon-neptune-tools with Apache License 2.0 7 votes vote down vote up
public ExportPropertyGraphTask<T> createExportTask(PropertiesMetadataCollection metadataCollection,
                                                   GraphTraversalSource g,
                                                   PropertyGraphTargetConfig targetConfig,
                                                   RangeFactory rangeFactory,
                                                   Status status,
                                                   int index) {
    return new ExportPropertyGraphTask<>(
            metadataCollection.propertyMetadataFor(graphElementType),
            labelsFilter,
            graphElementType.graphClient(g, tokensOnly, stats),
            graphElementType.writerFactory(),
            targetConfig,
            rangeFactory,
            status,
            index
    );
}
 
Example #2
Source File: ClassificationServiceCache.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Indicates whether or not the given {@link FileModel} is already attached to the {@link ClassificationModel}.
 *
 * Note that this assumes all {@link ClassificationModel} attachments are handled via the {@link ClassificationService}.
 *
 * Outside of tests, this should be a safe assumption to make.
 */
static boolean isClassificationLinkedToFileModel(GraphRewrite event, ClassificationModel classificationModel, FileModel fileModel)
{
    String key = getClassificationFileModelCacheKey(classificationModel, fileModel);
    Boolean linked = getCache(event).get(key);

    if (linked == null)
    {
        GraphTraversal<Vertex, Vertex> existenceCheck = new GraphTraversalSource(event.getGraphContext().getGraph()).V(classificationModel.getElement());
        existenceCheck.out(ClassificationModel.FILE_MODEL);
        existenceCheck.filter(vertexTraverser -> vertexTraverser.get().equals(fileModel.getElement()));

        linked = existenceCheck.hasNext();
        cacheClassificationFileModel(event, classificationModel, fileModel, linked);
    }
    return linked;
}
 
Example #3
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProperlyHandleBindings() throws Exception {
    final Graph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId(graph, "marko"));
    Assert.assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()"));

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("s", "marko");
    bindings.put("f", 0.5f);
    bindings.put("i", 1);
    bindings.put("b", true);
    bindings.put("l", 100l);
    bindings.put("d", 1.55555d);

    assertEquals(engine.eval("g.E().has('weight',f).next()", bindings), g.E(convertToEdgeId(graph, "marko", "knows", "vadas")).next());
    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
}
 
Example #4
Source File: EntityGraphFactory.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Load the data form the jCas into the given graph.
 *
 * @param jCas to load the data from
 * @param graph to load the data into
 * @throws AnalysisEngineProcessException
 */
public void load(JCas jCas, Graph graph, Features features)
    throws AnalysisEngineProcessException {

  try (Graph documentGraph = factory.create(jCas)) {
    GraphTraversalSource fromTraversal = documentGraph.traversal();

    GraphTraversalSource destTraversal = graph.traversal();

    mapEntities(features, fromTraversal, destTraversal);
    mapEvents(features, fromTraversal, destTraversal);
    mapRelations(features, fromTraversal, destTraversal);
  } catch (Exception e) {
    throw new AnalysisEngineProcessException(e);
  }
}
 
Example #5
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldTriggerAddVertexPropertyAdded() {
    final StubMutationListener listener1 = new StubMutationListener();
    final StubMutationListener listener2 = new StubMutationListener();
    final EventStrategy.Builder builder = EventStrategy.build()
            .addListener(listener1)
            .addListener(listener2);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();

    final Vertex vSome = graph.addVertex("some", "thing");
    vSome.property(VertexProperty.Cardinality.single, "that", "thing");
    final GraphTraversalSource gts = create(eventStrategy);
    gts.V().addV().property("this", "thing").next();

    tryCommit(graph, g -> assertEquals(1, IteratorUtils.count(gts.V().has("this", "thing"))));

    assertEquals(1, listener1.addVertexEventRecorded());
    assertEquals(1, listener2.addVertexEventRecorded());
    assertEquals(0, listener2.vertexPropertyChangedEventRecorded());
    assertEquals(0, listener1.vertexPropertyChangedEventRecorded());
}
 
Example #6
Source File: EntityGraphFactoryTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoEvents() throws UIMAException {

  EntityGraphOptions options = EntityGraphOptions.builder().withEvents(false).build();
  EntityGraphFactory factory = createfactory(options);

  JCas jCas = JCasFactory.createJCas();
  JCasTestGraphUtil.populateJcas(jCas);

  Graph graph = factory.create(jCas);

  final GraphTraversalSource traversal = graph.traversal();

  assertEquals(3, traversal.V().hasLabel(ENTITY).count().next().intValue());
  assertEquals(0, traversal.V().hasLabel(EVENT).count().next().intValue());
  assertEquals(0, traversal.E().hasLabel(PARTICIPANT_IN).count().next().intValue());
  assertEquals(2, traversal.E().hasLabel(RELATION).count().next().intValue());

  assertEquals(3, IteratorUtils.count(graph.vertices()));
  assertEquals(2, IteratorUtils.count(graph.edges()));
}
 
Example #7
Source File: MainGraphMapper.java    From egeria with Apache License 2.0 6 votes vote down vote up
/**
 * Add all the columns related to a table. This is needed  due to lack of Lineage Mappings
 * between input schema element and it's output.
 *
 * @param bufferG  - Traversal source for buffer Graph
 * @param mainG - Traversal source for main Graph
 * @param tableOut - table to add the columns
 * */
private void addColumns(GraphTraversalSource bufferG, GraphTraversalSource mainG, Vertex tableOut) {
    List<Vertex> columns =  bufferG.V().
                            has(PROPERTY_KEY_ENTITY_GUID,tableOut.property(PROPERTY_KEY_ENTITY_GUID).value()).
                            inE(NESTED_SCHEMA_ATTRIBUTE).
                            otherV().toList();

    List<String> guidList = columns.stream().map(v -> (String) v.property(PROPERTY_KEY_ENTITY_GUID).value()).collect(Collectors.toList());
    for(String guid: guidList) {

        Iterator<Vertex> columnToAdd = mainG.V().has(PROPERTY_KEY_ENTITY_NODE_ID, guid);
        if (!columnToAdd.hasNext()) {
            Vertex newColumn = mainG.addV(NODE_LABEL_COLUMN).property(PROPERTY_KEY_ENTITY_NODE_ID, guid).next();
            Vertex originalVertex = bufferG.V().has(PROPERTY_KEY_ENTITY_GUID, guid).next();
            copyVertexProperties(originalVertex, newColumn);
            addExtraProperties(mainG, bufferG, originalVertex, newColumn);

            Iterator<Vertex> columnVertex = mainG.V(newColumn.id()).bothE(EDGE_LABEL_INCLUDED_IN).otherV()
                    .has(PROPERTY_KEY_ENTITY_NODE_ID, tableOut.property(PROPERTY_KEY_ENTITY_GUID).value());
            if (!columnVertex.hasNext()) {
                newColumn.addEdge(EDGE_LABEL_INCLUDED_IN, tableOut);
            }
        }
    }
}
 
Example #8
Source File: MainGraphMapper.java    From egeria with Apache License 2.0 6 votes vote down vote up
private Vertex getTable(GraphTraversalSource bufferG,GraphTraversalSource mainG,Vertex asset){
    Iterator<Vertex> table = bufferG.V().has(PROPERTY_KEY_ENTITY_GUID,asset.property(PROPERTY_KEY_ENTITY_GUID).value())
            .emit().repeat(bothE().otherV().simplePath()).times(2).or(hasLabel(RELATIONAL_TABLE),hasLabel(DATA_FILE));

    if (!table.hasNext()){
        return null;
    }

    Vertex tableBuffer = table.next();
    Iterator<Vertex> tableVertex = mainG.V().has(PROPERTY_KEY_ENTITY_NODE_ID,tableBuffer.property(PROPERTY_KEY_ENTITY_GUID).value());
    if (!tableVertex.hasNext()) {
        Vertex newTable = mainG.addV(NODE_LABEL_TABLE)
                .property(PROPERTY_KEY_ENTITY_NODE_ID,
                        tableBuffer.property(PROPERTY_KEY_ENTITY_GUID).value())
                .next();
        copyVertexProperties(tableBuffer, newTable);
        return newTable;
    }

    return tableVertex.next();
}
 
Example #9
Source File: MainGraphConnectorHelper.java    From egeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a subgraph containing all leaf nodes of the full graph that are connected with the queried node.
 * The queried node can be a column or table.
 *
 * @param guid      The guid of the node of which the lineage is queried of. This can be a column or table node.
 * @param edgeLabels Traversed edges
 * @return a subgraph in the GraphSON format.
 */
LineageVerticesAndEdges ultimateDestination(String guid, String... edgeLabels) throws OpenLineageException {
    String methodName = "MainGraphConnector.ultimateDestination";
    GraphTraversalSource g = mainGraph.traversal();

    List<Vertex> destinationsList = g.V().has(GraphConstants.PROPERTY_KEY_ENTITY_NODE_ID, guid).
            until(outE(edgeLabels).count().is(0)).
            repeat(outE(edgeLabels).inV().simplePath()).
            dedup().toList();

    detectProblematicCycle(methodName, destinationsList);

    Vertex originalQueriedVertex = g.V().has(GraphConstants.PROPERTY_KEY_ENTITY_NODE_ID, guid).next();
    LineageVertex queriedVertex = abstractVertex(originalQueriedVertex);

    Set<LineageVertex> lineageVertices = new HashSet<>();
    Set<LineageEdge> lineageEdges = new HashSet<>();

    lineageVertices.add(queriedVertex);

    addDestinationCondensation(destinationsList, lineageVertices, lineageEdges, originalQueriedVertex, queriedVertex);
    LineageVerticesAndEdges lineageVerticesAndEdges = new LineageVerticesAndEdges(lineageVertices, lineageEdges);
    return lineageVerticesAndEdges;
}
 
Example #10
Source File: TinkerGraphPlayTest.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testPlay9() throws Exception {
    Graph graph = TinkerGraph.open();
    graph.io(GraphMLIo.build()).readGraph("../data/grateful-dead.xml");

    GraphTraversalSource g = graph.traversal().withComputer(Computer.compute().workers(4)).withStrategies(PathRetractionStrategy.instance());
    GraphTraversalSource h = graph.traversal().withComputer(Computer.compute().workers(4)).withoutStrategies(PathRetractionStrategy.class);

    for (final GraphTraversalSource source : Arrays.asList(g, h)) {
        System.out.println(source.V().match(
                __.as("a").in("sungBy").as("b"),
                __.as("a").in("sungBy").as("c"),
                __.as("b").out("writtenBy").as("d"),
                __.as("c").out("writtenBy").as("e"),
                __.as("d").has("name", "George_Harrison"),
                __.as("e").has("name", "Bob_Marley")).select("a").count().profile().next());
    }
}
 
Example #11
Source File: GremlinEnabledScriptEngineTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEvalBytecode() throws Exception {
    final GremlinScriptEngine scriptEngine = manager.getEngineByName(ENGINE_TO_TEST);
    final Graph graph = EmptyGraph.instance();
    final GraphTraversalSource g = graph.traversal();

    // purposefully use "x" to match the name of the traversal source binding for "x" below and
    // thus tests the alias added for "x"
    final GraphTraversal t = getTraversalWithLambda(g);

    final Bindings bindings = new SimpleBindings();
    bindings.put("x", g);

    final Traversal evald = scriptEngine.eval(t.asAdmin().getBytecode(), bindings, "x");

    assertTraversals(t, evald);

    assertThat(manager.getBindings().containsKey(GremlinScriptEngine.HIDDEN_G), is(false));
}
 
Example #12
Source File: BufferGraphConnector.java    From egeria with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the output column of a Process based on the input.
 * @param g - Graph traversal object
 * @param columnIn - THe vertex of the schema element before processing.
 * @param process - The vertex of the process.
 */
private void findOutputColumn(GraphTraversalSource g,Vertex columnIn,Vertex process){
    List<Vertex> schemaElementVertex = g.V()
                                        .has(PROPERTY_KEY_ENTITY_GUID, columnIn.property(PROPERTY_KEY_ENTITY_GUID).value())
                                        .in(LINEAGE_MAPPING)
                                        .toList();

    Vertex vertexToStart = null;
    if (schemaElementVertex != null) {
        Vertex columnOut = null;
        vertexToStart = getProcessForTheSchemaElement(g,schemaElementVertex,process);
        if (vertexToStart != null) {
            columnOut = findPathForOutputAsset(vertexToStart, g, columnIn);
        }
        moveColumnProcessColumn(columnIn, columnOut, process);
    }
}
 
Example #13
Source File: BytecodeTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIncludeBindingsInEquality() {
    final Bindings b = Bindings.instance();
    final GraphTraversalSource g = EmptyGraph.instance().traversal();

    final Bytecode bytecode1 = g.V().out(b.of("a", "created")).asAdmin().getBytecode();
    final Bytecode bytecode2 = g.V().out(b.of("a", "knows")).asAdmin().getBytecode();
    final Bytecode bytecode3 = g.V().out(b.of("b", "knows")).asAdmin().getBytecode();
    final Bytecode bytecode4 = g.V().out(b.of("b", "knows")).asAdmin().getBytecode();

    assertNotEquals(bytecode1, bytecode2);
    assertNotEquals(bytecode1, bytecode3);
    assertNotEquals(bytecode2, bytecode3);
    assertNotEquals(bytecode2, bytecode4);
    assertNotEquals(bytecode1, bytecode4);
    assertEquals(bytecode3, bytecode4);

    assertEquals(1, bytecode1.getBindings().size());
    assertEquals("created", bytecode1.getBindings().get("a"));
}
 
Example #14
Source File: MainGraphConnectorHelper.java    From egeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a subgraph containing all root of the full graph that are connected with the queried node.
 * The queried node can be a column or table.
 *
 * @param guid       The guid of the node of which the lineage is queried of. This can be a column or a table.
 * @param edgeLabels Traversed edges
 * @return a subgraph in the GraphSON format.
 */
LineageVerticesAndEdges ultimateSource(String guid, String... edgeLabels) throws OpenLineageException {
    String methodName = "MainGraphConnector.ultimateSource";
    GraphTraversalSource g = mainGraph.traversal();

    List<Vertex> sourcesList = g.V().has(GraphConstants.PROPERTY_KEY_ENTITY_NODE_ID, guid).
            until(inE(edgeLabels).count().is(0)).
            repeat(inE(edgeLabels).outV().simplePath()).
            dedup().toList();

    detectProblematicCycle(methodName, sourcesList);

    Vertex originalQueriedVertex = g.V().has(GraphConstants.PROPERTY_KEY_ENTITY_NODE_ID, guid).next();

    Set<LineageVertex> lineageVertices = new HashSet<>();

    Set<LineageEdge> lineageEdges = new HashSet<>();

    LineageVertex queriedVertex = abstractVertex(originalQueriedVertex);
    lineageVertices.add(queriedVertex);

    addSourceCondensation(sourcesList, lineageVertices, lineageEdges, originalQueriedVertex, queriedVertex);
    LineageVerticesAndEdges lineageVerticesAndEdges = new LineageVerticesAndEdges(lineageVertices, lineageEdges);
    return lineageVerticesAndEdges;
}
 
Example #15
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldTriggerAddVertexFromStart() {
    final StubMutationListener listener1 = new StubMutationListener();
    final StubMutationListener listener2 = new StubMutationListener();
    final EventStrategy.Builder builder = EventStrategy.build()
            .addListener(listener1)
            .addListener(listener2);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();

    graph.addVertex("some", "thing");
    final GraphTraversalSource gts = create(eventStrategy);
    gts.addV().property("any", "thing").next();

    tryCommit(graph, g -> assertEquals(1, IteratorUtils.count(gts.V().has("any", "thing"))));
    assertEquals(1, listener1.addVertexEventRecorded());
    assertEquals(1, listener2.addVertexEventRecorded());
}
 
Example #16
Source File: TechnologyTagService.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return an {@link Iterable} containing all {@link TechnologyTagModel}s that are directly associated with the provided {@link FileModel}.
 */
public Iterable<TechnologyTagModel> findTechnologyTagsForFile(FileModel fileModel)
{
    GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V(fileModel.getElement());
    pipeline.in(TechnologyTagModel.TECH_TAG_TO_FILE_MODEL).has(WindupVertexFrame.TYPE_PROP, TechnologyTagModel.TYPE);

    Comparator<TechnologyTagModel> comparator = new DefaultTechnologyTagComparator();
    pipeline.order().by((a, b) -> {
        TechnologyTagModel aModel = getGraphContext().getFramed().frameElement(a, TechnologyTagModel.class);
        TechnologyTagModel bModel = getGraphContext().getFramed().frameElement(b, TechnologyTagModel.class);

        return comparator.compare(aModel, bModel);
    });

    return new FramedVertexIterable<>(getGraphContext().getFramed(), pipeline.toList(), TechnologyTagModel.class);
}
 
Example #17
Source File: ElementIdStrategyProcessTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldGenerateDefaultIdOnGraphAddVWithGeneratedDefaultId() throws Exception {
    final ElementIdStrategy strategy = ElementIdStrategy.build().create();
    final GraphTraversalSource sg = create(strategy);
    final Vertex v = sg.addV().property("name", "stephen").next();
    assertEquals("stephen", v.value("name"));

    final Traversal t1 = graph.traversal().V(v);
    t1.asAdmin().applyStrategies();
    logger.info(t1.toString());

    final Traversal t2 = sg.V(v);
    t2.asAdmin().applyStrategies();
    logger.info(t2.toString());

    assertNotNull(UUID.fromString(sg.V(v).id().next().toString()));
}
 
Example #18
Source File: TinkerGraphTest.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
private static void generate(final Graph graph) {
    final int size = 100;
    final List<Object> ids = new ArrayList<>();
    final Vertex v = graph.addVertex("sin", 0.0f, "cos", 1.0f, "ii", 0f);
    ids.add(v.id());

    final GraphTraversalSource g = graph.traversal();

    final Random rand = new Random();
    for (int ii = 1; ii < size; ii++) {
        final Vertex t = graph.addVertex("ii", ii, "sin", Math.sin(ii / 5.0f), "cos", Math.cos(ii / 5.0f));
        final Vertex u = g.V(ids.get(rand.nextInt(ids.size()))).next();
        t.addEdge("linked", u);
        ids.add(u.id());
        ids.add(v.id());
    }
}
 
Example #19
Source File: GremlinEnabledScriptEngineTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowBytecodeEvalWithAliasInBindings() throws Exception {
    final GremlinScriptEngine scriptEngine = manager.getEngineByName(ENGINE_TO_TEST);
    final Graph graph = EmptyGraph.instance();
    final GraphTraversalSource g = graph.traversal();

    // purposefully use "x" to match the name of the traversal source binding for "x" below and
    // thus tests the alias added for "x"
    final GraphTraversal t = getTraversalWithLambda(g);

    final Bindings bindings = new SimpleBindings();
    bindings.put("x", g);
    bindings.put(GremlinScriptEngine.HIDDEN_G, g);

    scriptEngine.eval(t.asAdmin().getBytecode(), bindings, "x");
}
 
Example #20
Source File: ObjectQueryTest.java    From gremlin-ogm with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  marko = Person.of("marko");
  vertex = new DetachedVertex(
      1, "person", new HashMap<String, Object>() {
        {
          put("name", Arrays.asList(new HashMap() {
            {
              put("value", "marko");
            }
          }));
        }
      });

  g = mock(GraphTraversalSource.class);
  traversal = mock(GraphTraversal.class);

  when(g.V()).thenReturn(traversal);

  query = new ObjectQuery(g);
}
 
Example #21
Source File: GraphSONMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(map).create());
    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);

    assertNotNull(converted);

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(1000, converted.get("1").asInt());
}
 
Example #22
Source File: TinkerGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldOptionalUsingWithComputer() {
    // not all systems will have 3+ available processors (e.g. travis)
    assumeThat(Runtime.getRuntime().availableProcessors(), greaterThan(2));

    // didn't add this as a general test as it basically was only failing under a specific condition for
    // TinkerGraphComputer - see more here: https://issues.apache.org/jira/browse/TINKERPOP-1619
    final GraphTraversalSource g = TinkerFactory.createModern().traversal();

    final List<Edge> expected = g.E(7, 7, 8, 9).order().by(T.id).toList();
    assertEquals(expected, g.withComputer(Computer.compute().workers(3)).V(1, 2).optional(__.bothE().dedup()).order().by(T.id).toList());
    assertEquals(expected, g.withComputer(Computer.compute().workers(4)).V(1, 2).optional(__.bothE().dedup()).order().by(T.id).toList());
}
 
Example #23
Source File: ElementIdStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldGenerateDefaultIdOnGraphAddVWithGeneratedCustomId() throws Exception {
    final ElementIdStrategy strategy = ElementIdStrategy.build().idMaker(new ConstantSupplier<>("xxx")).create();
    final GraphTraversalSource sg = create(strategy);
    final Vertex v = sg.addV().property("name", "stephen").next();
    assertEquals("stephen", v.value("name"));
    assertEquals("xxx", sg.V(v).id().next());
    assertEquals("xxx", sg.V("xxx").id().next());
}
 
Example #24
Source File: ElementIdStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldGenerateDefaultIdOnGraphAddVWithSpecifiedId() throws Exception {
    final ElementIdStrategy strategy = ElementIdStrategy.build().create();
    final GraphTraversalSource sg = create(strategy);
    final Vertex v = sg.addV().property(T.id, "STEPHEN").property("name", "stephen").next();
    assertEquals("stephen", v.value("name"));
    assertEquals("STEPHEN", sg.V(v).id().next());
    assertEquals("STEPHEN", sg.V("STEPHEN").id().next());
}
 
Example #25
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldUseActualEdgeWhenRemoved() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final Edge e = v.addEdge("self", v, "dropped", "yay!");
    final String label = e.label();
    final Object inId = v.id();
    final Object outId = v.id();

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void edgeRemoved(final Edge element) {
            assertEquals(e, element);
            assertEquals(label, element.label());
            assertEquals(inId, element.inVertex().id());
            assertEquals(outId, element.outVertex().id());
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener).detach(EventStrategy.Detachment.REFERENCE);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.E(e).drop().iterate();
    tryCommit(graph);

    assertVertexEdgeCounts(graph, 1, 0);
    assertThat(triggered.get(), is(true));
}
 
Example #26
Source File: GraphOMRSMetadataStore.java    From egeria with Apache License 2.0 5 votes vote down vote up
synchronized void updateRelationshipInStore(Relationship relationship)
        throws
        RepositoryErrorException
{

    String methodName = "updateRelationshipInStore";

    String guid = relationship.getGUID();
    GraphTraversalSource g = instanceGraph.traversal();

    Iterator<Edge> edgeIt = g.E().hasLabel("Relationship").has(PROPERTY_KEY_RELATIONSHIP_GUID, guid);

    if (edgeIt.hasNext()) {
        Edge edge = edgeIt.next();
        log.debug("{} found existing edge {}", methodName, edge);

        try {

            relationshipMapper.mapRelationshipToEdge(relationship, edge);

        } catch (Exception e) {

            log.error("{} Caught exception from relationship mapper {}", methodName, e.getMessage());
            g.tx().rollback();
            throw new RepositoryErrorException(GraphOMRSErrorCode.RELATIONSHIP_NOT_UPDATED.getMessageDefinition(relationship.getGUID(), methodName,
                                                                                                                this.getClass().getName(),
                                                                                                                repositoryName),
                    this.getClass().getName(),
                    methodName, e);
        }
    }

    g.tx().commit();
}
 
Example #27
Source File: HibernateEntityService.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets an {@link Iterable} of {@link }s for the given {@link ProjectModel}.
 */
public Iterable<HibernateEntityModel> findAllByApplication(ProjectModel application)
{
    GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V(application.getElement());
    pipeline.in(HibernateEntityModel.APPLICATIONS);
    pipeline.has(WindupVertexFrame.TYPE_PROP, Text.textContains(HibernateEntityModel.TYPE));

    return new FramedVertexIterable<>(getGraphContext().getFramed(), pipeline.toList(), HibernateEntityModel.class);
}
 
Example #28
Source File: TransactionImpl.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private void merge(ConceptId duplicateId, ConceptId targetId) {
    GraphTraversalSource tinkerTraversal = janusTraversalSourceProvider.getTinkerTraversal();
    Vertex duplicate = tinkerTraversal.V(Schema.elementId(duplicateId)).next();
    Vertex mergeTargetV = tinkerTraversal.V(Schema.elementId(targetId)).next();

    duplicate.vertices(Direction.IN).forEachRemaining(connectedVertex -> {
        // merge attribute edge connecting 'duplicate' and 'connectedVertex' to 'mergeTargetV', if exists
        GraphTraversal<Vertex, Edge> attributeEdge =
                tinkerTraversal.V(duplicate).inE(Schema.EdgeLabel.ATTRIBUTE.getLabel()).filter(__.outV().is(connectedVertex));
        if (attributeEdge.hasNext()) {
            mergeAttributeEdge(mergeTargetV, connectedVertex, attributeEdge);
        }

        // merge role-player edge connecting 'duplicate' and 'connectedVertex' to 'mergeTargetV', if exists
        GraphTraversal<Vertex, Edge> rolePlayerEdge =
                tinkerTraversal.V(duplicate).inE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()).filter(__.outV().is(connectedVertex));
        if (rolePlayerEdge.hasNext()) {
            mergeRolePlayerEdge(mergeTargetV, rolePlayerEdge);
        }
        try {
            attributeEdge.close();
            rolePlayerEdge.close();
        } catch (Exception e) {
            LOG.warn("Error closing the merging traversals", e);
        }
    });
    duplicate.remove();
}
 
Example #29
Source File: MainGraphConnectorHelper.java    From egeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a subgraph containing all columns or tables connected to the queried glossary term, as well as all
 * columns or tables connected to synonyms of the queried glossary term.
 *
 * @param guid The guid of the glossary term of which the lineage is queried of.
 * @return a subgraph in the GraphSON format.
 */
LineageVerticesAndEdges glossary(String guid) {
    GraphTraversalSource g = mainGraph.traversal();

    Graph subGraph = (Graph)
            g.V().has(GraphConstants.PROPERTY_KEY_ENTITY_NODE_ID, guid)
                    .emit().
                    repeat(bothE(EDGE_LABEL_GLOSSARYTERM_TO_GLOSSARYTERM).subgraph("subGraph").simplePath().otherV())
                    .inE(EDGE_LABEL_SEMANTIC).subgraph("subGraph").outV()
                    .cap("subGraph").next();

    LineageVerticesAndEdges lineageVerticesAndEdges = getLineageVerticesAndEdges(subGraph);
    return lineageVerticesAndEdges;
}
 
Example #30
Source File: DocumentGraphFactory.java    From baleen with Apache License 2.0 5 votes vote down vote up
private Optional<Vertex> loadDocument(JCas jCas, GraphTraversalSource traversal) {
  String documentId = getDocumentId(jCas);
  if (options.isOutputDocument()) {
    Vertex documentVert =
        traversal
            .addV(DOCUMENT)
            .property(T.id, coerce(documentId))
            .sideEffect(
                tv -> {
                  Vertex documentVertex = tv.get();
                  getGraphMetadata(jCas).entrySet().stream()
                      .forEach(e -> setProperty(documentVertex, e.getKey(), e.getValue()));
                })
            .next();

    traversal
        .V()
        .filter(v -> !v.get().equals(documentVert))
        .addE(MENTION_IN)
        .to(documentVert)
        .iterate();
    return Optional.of(documentVert);
  } else {
    traversal.V().property(FIELD_DOCUMENT_ID, coerce(documentId)).iterate();
    traversal.E().property(FIELD_DOCUMENT_ID, coerce(documentId)).iterate();
    return Optional.empty();
  }
}