org.apache.tinkerpop.gremlin.structure.Direction Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Direction. 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: TestTopology.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testTopologyTraversal() {
    Vertex gis = this.sqlgGraph.addVertex(T.label, "Gis", "name", "HaloGis1");
    Vertex something = this.sqlgGraph.addVertex(T.label, "Something", "name", "Something1");
    gis.addEdge("testEdge", something, "edgeProperty", "asdasd");
    this.sqlgGraph.tx().commit();
    Assert.assertEquals(2, this.sqlgGraph.topology().V().hasLabel("sqlg_schema.schema").out("schema_vertex").count().next().intValue());
    Assert.assertEquals(2, this.sqlgGraph.topology().V().hasLabel("sqlg_schema.vertex").in("schema_vertex").count().next().intValue());
    Assert.assertEquals(2, this.sqlgGraph.topology().V().hasLabel("sqlg_schema.vertex").out("vertex_property").count().next().intValue());
    Assert.assertEquals(2, this.sqlgGraph.topology().V().hasLabel("sqlg_schema.property").in("vertex_property").count().next().intValue());
    Assert.assertEquals(1, this.sqlgGraph.topology().V().hasLabel("sqlg_schema.property").in("edge_property").count().next().intValue());

    Vertex v = this.sqlgGraph.topology().V().hasLabel("sqlg_schema.schema").has("name", "public").next();
    Assert.assertTrue(v.edges(Direction.OUT, "schema_vertex").hasNext());

    Assert.assertEquals(2, this.sqlgGraph.topology().V().hasLabel("sqlg_schema.schema").as("schema").select("schema").out("schema_vertex").count().next().intValue());
    Assert.assertEquals(2, this.sqlgGraph.topology().V().hasLabel("sqlg_schema.schema").as("schema").values("name").as("schemaName").select("schema").out("schema_vertex").count().next().intValue());
    Assert.assertTrue(this.sqlgGraph.topology().V().hasLabel("sqlg_schema.schema").as("schema").values("name").as("schemaName").select("schema").out("schema_vertex").hasNext());

    Assert.assertEquals("testEdge", this.sqlgGraph.topology().V().hasLabel("sqlg_schema.property").in("edge_property").values("name").next());
}
 
Example #2
Source File: VertexDuplicator.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
static void moveOutgoingEdges(Vertex vertex, Vertex duplicate, IndexHandler indexHandler) {
  for (Iterator<Edge> edges = vertex.edges(Direction.OUT); edges.hasNext(); ) {
    Edge edge = edges.next();
    if (edge.label().equals(VERSION_OF)) {
      continue;
    }

    Edge duplicateEdge = duplicate.addEdge(edge.label(), edge.inVertex());

    for (Iterator<Property<Object>> properties = edge.properties(); properties.hasNext(); ) {
      Property<Object> property = properties.next();

      duplicateEdge.property(property.key(), property.value());
    }
    if (duplicateEdge.<Boolean>property("isLatest").orElse(false)) {
      duplicateEdge.<String>property("tim_id")
        .ifPresent(p -> indexHandler.upsertIntoEdgeIdIndex(UUID.fromString(p), duplicateEdge));
    }
    edge.remove();
  }
}
 
Example #3
Source File: StarGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void shouldAttachWithGetMethod() {
    // vertex host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, StarGraph.of(vertex).getStarVertex().attach(Attachable.Method.get(vertex))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, ((Attachable<VertexProperty>) vertexProperty).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(vertex))))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, ((Attachable<Edge>) edge).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(vertex))))));

    // graph host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, StarGraph.of(vertex).getStarVertex().attach(Attachable.Method.get(graph))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, ((Attachable<VertexProperty>) vertexProperty).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(graph))))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, ((Attachable<Edge>) edge).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(graph))))));
}
 
Example #4
Source File: StarGraphSerializer.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private <I extends InputShim> void readEdges(final KryoShim<I, ?> kryo, final I input, final StarGraph starGraph, final Direction direction) {
    if (kryo.readObject(input, Boolean.class)) {
        final int numberOfUniqueLabels = kryo.readObject(input, Integer.class);
        for (int i = 0; i < numberOfUniqueLabels; i++) {
            final String edgeLabel = kryo.readObject(input, String.class);
            final int numberOfEdgesWithLabel = kryo.readObject(input, Integer.class);
            for (int j = 0; j < numberOfEdgesWithLabel; j++) {
                final Object edgeId = kryo.readClassAndObject(input);
                final Object adjacentVertexId = kryo.readClassAndObject(input);
                if (this.graphFilter.checkEdgeLegality(direction, edgeLabel).positive()) {
                    if (direction.equals(Direction.OUT))
                        starGraph.starVertex.addOutEdge(edgeLabel, starGraph.addVertex(T.id, adjacentVertexId), T.id, edgeId);
                    else
                        starGraph.starVertex.addInEdge(edgeLabel, starGraph.addVertex(T.id, adjacentVertexId), T.id, edgeId);
                } else if (null != starGraph.edgeProperties) {
                    starGraph.edgeProperties.remove(edgeId);
                }
            }
        }
    }
}
 
Example #5
Source File: Neo4jVertex.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<Vertex> vertices(final Direction direction, final String... edgeLabels) {
    this.graph.tx().readWrite();
    return new Iterator<Vertex>() {
        final Iterator<Neo4jRelationship> relationshipIterator = 0 == edgeLabels.length ?
                BOTH == direction ?
                        IteratorUtils.concat(getBaseVertex().relationships(Neo4jHelper.mapDirection(OUT)).iterator(),
                                getBaseVertex().relationships(Neo4jHelper.mapDirection(IN)).iterator()) :
                        getBaseVertex().relationships(Neo4jHelper.mapDirection(direction)).iterator() :
                BOTH == direction ?
                        IteratorUtils.concat(getBaseVertex().relationships(Neo4jHelper.mapDirection(OUT), (edgeLabels)).iterator(),
                                getBaseVertex().relationships(Neo4jHelper.mapDirection(IN), (edgeLabels)).iterator()) :
                        getBaseVertex().relationships(Neo4jHelper.mapDirection(direction), (edgeLabels)).iterator();

        @Override
        public boolean hasNext() {
            return this.relationshipIterator.hasNext();
        }

        @Override
        public Neo4jVertex next() {
            return new Neo4jVertex(this.relationshipIterator.next().other(getBaseVertex()), graph);
        }
    };
}
 
Example #6
Source File: SparkMessenger.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public void sendMessage(final MessageScope messageScope, final M message) {
    if (messageScope instanceof MessageScope.Local) {
        final MessageScope.Local<M> localMessageScope = (MessageScope.Local) messageScope;
        final Traversal.Admin<Vertex, Edge> incidentTraversal = SparkMessenger.setVertexStart(localMessageScope.getIncidentTraversal().get().asAdmin(), this.vertex);
        final Direction direction = SparkMessenger.getOppositeDirection(incidentTraversal);

        // handle processing for BOTH given TINKERPOP-1862 where the target of the message is the one opposite
        // the current vertex
        incidentTraversal.forEachRemaining(edge -> {
            if (direction.equals(Direction.IN) || direction.equals(Direction.OUT))
                this.outgoingMessages.add(new Tuple2<>(edge.vertices(direction).next().id(), localMessageScope.getEdgeFunction().apply(message, edge)));
            else
                this.outgoingMessages.add(new Tuple2<>(edge instanceof StarGraph.StarOutEdge ? edge.inVertex().id() : edge.outVertex().id(), localMessageScope.getEdgeFunction().apply(message, edge)));

        });
    } else {
        ((MessageScope.Global) messageScope).vertices().forEach(v -> this.outgoingMessages.add(new Tuple2<>(v.id(), message)));
    }
}
 
Example #7
Source File: BitsyEdge.java    From bitsy with Apache License 2.0 5 votes vote down vote up
public UUID getVertexId(Direction dir) {
    if (dir == Direction.IN) {
        return inVertexId;
    } else if (dir == Direction.OUT) {
        return outVertexId;
    } else {
        throw new IllegalArgumentException("Unsupported direction " + dir);
    }
}
 
Example #8
Source File: SpecializedElementsWithOndiskTest.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnElementRefs() {
    TinkerGraph graph = newGratefulDeadGraphWithSpecializedElements();

    Vertex v0 = graph.addVertex(T.label, Song.label, Song.NAME, "Song 1");
    Vertex v2 = graph.addVertex(T.label, Song.label, Song.NAME, "Song 2");
    Edge e4 = v0.addEdge(FollowedBy.label, v2);
    assertTrue(v0 instanceof VertexRef);
    assertTrue(e4 instanceof EdgeRef);
    assertTrue(v0.edges(Direction.OUT).next() instanceof EdgeRef);
    assertTrue(v0.vertices(Direction.OUT).next() instanceof VertexRef);
}
 
Example #9
Source File: ApplicationReportIndexService.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return a global application index (not associated with a specific {@link ProjectModel}).
 */
public ApplicationReportIndexModel getOrCreateGlobalApplicationIndex()
{
    GraphTraversal<Vertex, Vertex> pipeline = getGraphContext().getGraph().traversal().V();
    pipeline.has(WindupVertexFrame.TYPE_PROP, ApplicationReportModel.TYPE);
    pipeline.filter(it -> !it.get().edges(Direction.OUT, ApplicationReportIndexModel.APPLICATION_REPORT_INDEX_TO_PROJECT_MODEL).hasNext());

    final ApplicationReportIndexModel result = pipeline.hasNext() ? frame(pipeline.next()) : create();
    return result;
}
 
Example #10
Source File: BlazeGraph.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup edges from a source vertex.
 * 
 * @see Vertex#edges(Direction, String...)
 */
CloseableIterator<Edge> edgesFromVertex(final BlazeVertex src, 
        final Direction dir, final String... edgeLabels) {
    final List<URI> uris = 
            Stream.of(edgeLabels).map(vf::typeURI).collect(toList());
    final String queryStr = sparql.edgesFromVertex(src, dir, uris);
    
    final Stream<Edge> stream = _select(queryStr, nextQueryId())
            .map(transforms.edge);
    return CloseableIterator.of(stream);
}
 
Example #11
Source File: IDHandler.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
public Direction getDirection() {
    switch (this) {
        case PROPERTY_DIR:
        case EDGE_OUT_DIR:
            return Direction.OUT;
        case EDGE_IN_DIR:
            return Direction.IN;
        default:
            throw new AssertionError();
    }
}
 
Example #12
Source File: TypeImpl.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public T unplay(Role role) {
    checkSchemaMutationAllowed();
    deleteEdge(Direction.OUT, Schema.EdgeLabel.PLAYS, (Concept) role);
    cachedDirectPlays.ifCached(set -> set.remove(role));
    ((RoleImpl) role).deleteCachedDirectPlaysByType(this);

    trackRolePlayers();

    return getThis();
}
 
Example #13
Source File: SparkSingleIterationStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    final Graph graph = traversal.getGraph().orElse(EmptyGraph.instance()); // best guess at what the graph will be as its dynamically determined
    for (final TraversalVertexProgramStep step : TraversalHelper.getStepsOfClass(TraversalVertexProgramStep.class, traversal)) {
        final Traversal.Admin<?, ?> computerTraversal = step.generateProgram(graph, EmptyMemory.instance()).getTraversal().get().clone();
        if (!computerTraversal.isLocked())
            computerTraversal.applyStrategies();
        ///
        boolean doesMessagePass = TraversalHelper.hasStepOfAssignableClassRecursively(Scope.global, MULTI_ITERATION_CLASSES, computerTraversal);
        if (!doesMessagePass) {
            for (final VertexStep vertexStep : TraversalHelper.getStepsOfAssignableClassRecursively(Scope.global, VertexStep.class, computerTraversal)) {
                if (vertexStep.returnsVertex() || !vertexStep.getDirection().equals(Direction.OUT)) { // in-edges require message pass in OLAP
                    doesMessagePass = true;
                    break;
                }
            }
        }
        if (!doesMessagePass &&
                !MessagePassingReductionStrategy.endsWithElement(computerTraversal.getEndStep()) &&
                !(computerTraversal.getTraverserRequirements().contains(TraverserRequirement.LABELED_PATH) || // TODO: remove this when dynamic detachment is available in 3.3.0
                        computerTraversal.getTraverserRequirements().contains(TraverserRequirement.PATH))) {  // TODO: remove this when dynamic detachment is available in 3.3.0
            step.setComputer(step.getComputer()
                    // if no message passing, don't partition the loaded graph
                    .configure(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, true)
                    // if no message passing, don't cache the loaded graph
                    .configure(Constants.GREMLIN_SPARK_SKIP_GRAPH_CACHE, true));
        }
    }
}
 
Example #14
Source File: StandardEdgeLabelMaker.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Override
public EdgeLabel make() {
    TypeDefinitionMap definition = makeDefinition();
    Preconditions.checkArgument(unidirectionality==Direction.BOTH || !getMultiplicity().isUnique(unidirectionality.opposite()),
            "Unidirectional labels cannot have restricted multiplicity at the other end");
    Preconditions.checkArgument(unidirectionality==Direction.BOTH || !hasSortKey() ||
            !getMultiplicity().isUnique(unidirectionality),
            "Unidirectional labels with restricted multiplicity cannot have a sort key");
    Preconditions.checkArgument(unidirectionality!=Direction.IN || definition.getValue(INVISIBLE,Boolean.class));


    definition.setValue(UNIDIRECTIONAL, unidirectionality);
    return tx.makeEdgeLabel(getName(), definition);
}
 
Example #15
Source File: AtlasJanusVertex.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
public long getEdgesCount(AtlasEdgeDirection dir, String edgeLabel) {
    Direction      direction = AtlasJanusObjectFactory.createDirection(dir);
    Iterator<Edge> it     = getWrappedElement().edges(direction, edgeLabel);
    IteratorToIterableAdapter<Edge> iterable = new IteratorToIterableAdapter<>(it);
    return StreamSupport.stream(iterable.spliterator(), true).count();
}
 
Example #16
Source File: DerivedPropertyValueGetter.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<String> getValues(Vertex vertex, String propertyName) {
  List<String> result = new ArrayList<>();
  vertex.vertices(Direction.BOTH, relations).forEachRemaining(targetVertex -> {
    targetVertex.vertices(Direction.BOTH, relationNames).forEachRemaining(finalVertex -> {
      if (finalVertex.property(propertyName).isPresent()) {
        result.add((String) finalVertex.property(propertyName).value());
      }
    });
  });
  return result;
}
 
Example #17
Source File: Neo4JEdge.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Iterator<Vertex> vertices(Direction direction) {
    // transaction should be ready for io operations
    graph.tx().readWrite();
    // out direction
    if (direction == Direction.OUT)
        return Stream.of((Vertex)out).iterator();
    // in direction
    if (direction == Direction.IN)
        return Stream.of((Vertex)in).iterator();
    // both
    return Stream.of((Vertex)out, in).iterator();
}
 
Example #18
Source File: AtlasJanusObjectFactory.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the Janus direction corresponding to the given
 * AtlasEdgeDirection.
 *
 * @param dir
 * @return
 */
public static Direction createDirection(AtlasEdgeDirection dir) {

    switch(dir) {
    case IN:
        return Direction.IN;
    case OUT:
        return Direction.OUT;
    case BOTH:
        return Direction.BOTH;
    default:
        throw new RuntimeException("Unrecognized direction: " + dir);
    }
}
 
Example #19
Source File: ForeignKey.java    From sqlg with MIT License 5 votes vote down vote up
private ForeignKey(String key) {
    this.compositeKeys.add(key);
    this.concatenatedIdentifiers += key;
    this.direction = key.endsWith(Topology.IN_VERTEX_COLUMN_END) ? Direction.IN : Direction.OUT;
    int indexOfDot = key.indexOf(".");
    String foreignKeySchema = key.substring(0, indexOfDot);
    String foreignKeyTable = key.substring(indexOfDot + 1);
    this.schemaTable = SchemaTable.of(foreignKeySchema, foreignKeyTable);
}
 
Example #20
Source File: RelationIT.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void whenAttributeLinkedToRelationIsInferred_EnsureItIsMarkedAsInferred(){
    AttributeType attributeType = tx.putAttributeType("Another thing of sorts", AttributeType.ValueType.STRING);
    RelationType relationType = tx.putRelationType("A thing of sorts").has(attributeType);

    Attribute attribute = attributeType.create("Things");
    Relation relation = relationType.create();

    relation.attributeInferred(attribute);
    assertTrue(ConceptVertex.from(relation).vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ATTRIBUTE)
            .anyMatch(edge -> edge.propertyBoolean(Schema.EdgeProperty.IS_INFERRED)));
}
 
Example #21
Source File: DirectionCondition.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean evaluate(E element) {
    if (direction==Direction.BOTH) return true;
    if (element instanceof CacheEdge) {
        return direction==((CacheEdge)element).getVertexCentricDirection();
    } else if (element instanceof TitanEdge) {
        return ((TitanEdge)element).vertex(direction).equals(baseVertex);
    } else if (element instanceof TitanVertexProperty) {
        return direction==Direction.OUT;
    }
    return false;
}
 
Example #22
Source File: EdgeIndexModel.java    From hgraphdb with Apache License 2.0 5 votes vote down vote up
public Edge deserialize(Result result) {
    byte[] bytes = result.getRow();
    PositionedByteRange buffer = new SimplePositionedByteRange(bytes);
    Object vertexId1 = ValueUtils.deserializeWithSalt(buffer);
    Direction direction = OrderedBytes.decodeInt8(buffer) == 1 ? Direction.IN : Direction.OUT;
    boolean isUnique = OrderedBytes.decodeInt8(buffer) == 1;
    String key = OrderedBytes.decodeString(buffer);
    String label = OrderedBytes.decodeString(buffer);
    Object value = ValueUtils.deserialize(buffer);
    Object vertexId2;
    Object edgeId;
    if (isUnique) {
        Cell vertexId2Cell = result.getColumnLatestCell(Constants.DEFAULT_FAMILY_BYTES, Constants.VERTEX_ID_BYTES);
        vertexId2 = ValueUtils.deserialize(CellUtil.cloneValue(vertexId2Cell));
        Cell edgeIdCell = result.getColumnLatestCell(Constants.DEFAULT_FAMILY_BYTES, Constants.EDGE_ID_BYTES);
        edgeId = ValueUtils.deserialize(CellUtil.cloneValue(edgeIdCell));
    } else {
        vertexId2 = ValueUtils.deserialize(buffer);
        edgeId = ValueUtils.deserialize(buffer);
    }
    Cell createdAttsCell = result.getColumnLatestCell(Constants.DEFAULT_FAMILY_BYTES, Constants.CREATED_AT_BYTES);
    Long createdAt = ValueUtils.deserialize(CellUtil.cloneValue(createdAttsCell));
    Map<String, Object> properties = new HashMap<>();
    properties.put(key, value);
    HBaseEdge newEdge;
    if (direction == Direction.IN) {
        newEdge = new HBaseEdge(graph, edgeId, label, createdAt, null, properties, false,
                graph.findOrCreateVertex(vertexId1),
                graph.findOrCreateVertex(vertexId2));
    } else {
        newEdge = new HBaseEdge(graph, edgeId, label, createdAt, null, properties, false,
                graph.findOrCreateVertex(vertexId2),
                graph.findOrCreateVertex(vertexId1));
    }
    HBaseEdge edge = (HBaseEdge) graph.findOrCreateEdge(edgeId);
    edge.copyFrom(newEdge);
    edge.setIndexKey(new IndexMetadata.Key(ElementType.EDGE, label, key));
    edge.setIndexTs(createdAttsCell.getTimestamp());
    return edge;
}
 
Example #23
Source File: Neo4jLuceneEntityFetcher.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Vertex> getVertexByIndex(GraphTraversalSource source, UUID id, String collectionName) {
  // Look up the vertex for this neo4j Node
  Optional<Vertex> vertexOpt = indexHandler.findById(id);

  // Return if the neo4j Node ID matches no vertex (extreme edge case)
  if (!vertexOpt.isPresent()) {
    LOG.error(Logmarkers.databaseInvariant,
      "Vertex with tim_id {} is found in index with id {}L but not in graph database", id);
    return Optional.empty();
  }

  // Get the latest version of the found Vertex
  Vertex foundVertex = vertexOpt.get();
  int infinityGuard = 0;
  while (foundVertex.vertices(Direction.OUT, "VERSION_OF").hasNext()) {
    // The neo4j index Node is one version_of behind the actual node
    foundVertex = foundVertex.vertices(Direction.OUT, "VERSION_OF").next();
    if (++infinityGuard >= MAX_VERSION_OF_DEPTH) {
      LOG.error(Logmarkers.databaseInvariant, "Vertices with tim_id {} might have circular VERSION_OF", id);
      return Optional.empty();
    }
  }

  // Only if this latest version is truly registered as latest return this as a successful hit
  if (foundVertex.value("isLatest")) {
    return Optional.of(foundVertex);
  } else {
    LOG.error(Logmarkers.databaseInvariant,
      "Last version of vertex with tim_id {} is not marked as isLatest=true", id);
  }

  // Failed to find vertex in lucene index, so return
  return Optional.empty();
}
 
Example #24
Source File: ArangoDBUtil.java    From arangodb-tinkerpop-provider with Apache License 2.0 5 votes vote down vote up
/**
 * Translate a Gremlin direction to Arango direction
 * @param direction
 * @return
 */
public static ArangoDBQueryBuilder.Direction getArangoDirectionFromGremlinDirection(final Direction direction) {
	switch (direction) {
		case BOTH:
			return ArangoDBQueryBuilder.Direction.ALL;
		case IN:
			return ArangoDBQueryBuilder.Direction.IN;
		case OUT:
			return ArangoDBQueryBuilder.Direction.OUT;
	}
	return null;
}
 
Example #25
Source File: StandardChangeState.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<TitanEdge> getEdges(final Vertex vertex, final Change change, final Direction dir, final String... labels) {
    final Set<String> stypes = toSet(labels);
    return (Iterable)getRelations(change, new Predicate<TitanRelation>() {
        @Override
        public boolean apply(@Nullable TitanRelation titanRelation) {
            return titanRelation.isEdge() && titanRelation.isIncidentOn(vertex) &&
                    (dir==Direction.BOTH || ((TitanEdge)titanRelation).vertex(dir).equals(vertex)) &&
                    (stypes.isEmpty() || stypes.contains(titanRelation.getType().name()));
        }
    });
}
 
Example #26
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadImports() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engineWithImports = new GremlinGroovyScriptEngine();
    engineWithImports.put("g", g);
    assertEquals(Vertex.class.getName(), engineWithImports.eval("Vertex.class.getName()"));
    assertEquals(2l, engineWithImports.eval("g.V().has('age',gt(30)).count().next()"));
    assertEquals(Direction.IN, engineWithImports.eval("Direction.IN"));
    assertEquals(Direction.OUT, engineWithImports.eval("Direction.OUT"));
    assertEquals(Direction.BOTH, engineWithImports.eval("Direction.BOTH"));
}
 
Example #27
Source File: MessagePassingReductionStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static final boolean endsWithElement(Step<?, ?> currentStep) {
    while (!(currentStep instanceof EmptyStep)) {
        if (currentStep instanceof VertexStep) // only inE, in, and out send messages
            return (((VertexStep) currentStep).returnsVertex() || !((VertexStep) currentStep).getDirection().equals(Direction.OUT));
        else if (currentStep instanceof EdgeVertexStep) // TODO: add GraphStep but only if its mid-traversal V()/E()
            return true;
        else if (currentStep instanceof TraversalFlatMapStep || currentStep instanceof TraversalMapStep || currentStep instanceof LocalStep)
            return endsWithElement(((TraversalParent) currentStep).getLocalChildren().get(0).getEndStep());
        else if (!(currentStep instanceof FilterStep || currentStep instanceof SideEffectStep || currentStep instanceof IdentityStep || currentStep instanceof Barrier))
            return false;
        currentStep = currentStep.getPreviousStep();
    }
    return false;
}
 
Example #28
Source File: JavaClassVertex.java    From Ferma with Apache License 2.0 4 votes vote down vote up
@Adjacency(label = "implements", direction = Direction.BOTH, operation = Adjacency.Operation.GET) 
<V extends JavaInterfaceVertex> Iterator<V> getImplementedInterfacesBoth(Class<V> types);
 
Example #29
Source File: StandardEdgeLabelMaker.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public StandardEdgeLabelMaker unidirected() {
    return unidirected(Direction.OUT);
}
 
Example #30
Source File: StarGraphGryoSerializer.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
public static StarGraphGryoSerializer withGraphFilter(final GraphFilter graphFilter) {
    final StarGraphGryoSerializer serializer = new StarGraphGryoSerializer(Direction.BOTH, graphFilter.clone());
    return serializer;
}