Java Code Examples for org.apache.tinkerpop.gremlin.structure.Element

The following are top voted examples for showing how to use org.apache.tinkerpop.gremlin.structure.Element. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gremlin-ogm   File: AddV.java   View source code 7 votes vote down vote up
@Override
@SneakyThrows
public GraphTraversal<Element, Element> apply(GraphTraversalSource g) {
  GraphTraversal traversal = g.addV(element.label());
  if (element.id() != null && HasFeature.Verifier.of(g)
      .verify(supportsUserSuppliedIds(element))) {
    traversal.property(T.id, element.id());
  }
  for (Field field : keyFields(element)) {
    String key = propertyKey(field);
    Object value = propertyValue(field, element);
    if (isMissing(value)) {
      throw org.apache.tinkerpop.gremlin.object.structure.Element.Exceptions.requiredKeysMissing(
          element.getClass(), key);
    }
    traversal.property(key, value);
  }
  return traversal;
}
 
Example 2
Project: gremlin-ogm   File: Select.java   View source code 6 votes vote down vote up
@Override
public GraphTraversal<Element, Map<String, Object>> apply(
    GraphTraversal<Element, Element> traversal) {
  GraphTraversal<Element, Map<String, Object>> selectTraversal;
  if (selectKey2 == null) {
    selectTraversal = traversal.select(selectKey1);
  } else {
    selectTraversal =
        traversal.select(selectKey1, selectKey2, otherSelectKeys.toArray(new String[] {}));
  }
  if (selectKey1 != null) {
    selectTraversal.by();
  }
  if (selectKey2 != null) {
    selectTraversal.by();
  }
  otherSelectKeys.forEach(otherSelectKey -> {
    selectTraversal.by();
  });
  return selectTraversal;
}
 
Example 3
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 6 votes vote down vote up
private <T extends Element> Iterator<T> createElementIterator(final Class<T> clazz, final Map<Object, T> elements,
                                                              final IdManager idManager,
                                                              final Object... ids) {
    final Iterator<T> iterator;
    if (0 == ids.length) {
        iterator = elements.values().iterator();
    } else {
        final List<Object> idList = Arrays.asList(ids);
        validateHomogenousIds(idList);

        // if the type is of Element - have to look each up because it might be an Attachable instance or
        // other implementation. the assumption is that id conversion is not required for detached
        // stuff - doesn't seem likely someone would detach a Titan vertex then try to expect that
        // vertex to be findable in OrientDB
        return clazz.isAssignableFrom(ids[0].getClass()) ?
                IteratorUtils.filter(IteratorUtils.map(idList, id -> elements.get(clazz.cast(id).id())).iterator(), Objects::nonNull)
                : IteratorUtils.filter(IteratorUtils.map(idList, id -> elements.get(idManager.convert(id))).iterator(), Objects::nonNull);
    }
    return TinkerHelper.inComputerMode(this) ?
            (Iterator<T>) (clazz.equals(Vertex.class) ?
                    IteratorUtils.filter((Iterator<Vertex>) iterator, t -> this.graphComputerView.legalVertex(t)) :
                    IteratorUtils.filter((Iterator<Edge>) iterator, t -> this.graphComputerView.legalEdge(t.outVertex(), t))) :
            iterator;
}
 
Example 4
Project: tinkergraph-gremlin   File: TinkerGraphCountStrategy.java   View source code 6 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    if (!(traversal.getParent() instanceof EmptyStep) || TraversalHelper.onGraphComputer(traversal))
        return;
    final List<Step> steps = traversal.getSteps();
    if (steps.size() < 2 ||
            !(steps.get(0) instanceof GraphStep) ||
            0 != ((GraphStep) steps.get(0)).getIds().length ||
            !(steps.get(steps.size() - 1) instanceof CountGlobalStep))
        return;
    for (int i = 1; i < steps.size() - 1; i++) {
        final Step current = steps.get(i);
        if (!(current instanceof MapStep ||
                current instanceof IdentityStep ||
                current instanceof NoOpBarrierStep ||
                current instanceof CollectingBarrierStep) ||
                (current instanceof TraversalParent &&
                        TraversalHelper.anyStepRecursively(s -> (s instanceof SideEffectStep || s instanceof AggregateStep), (TraversalParent) current)))
            return;
    }
    final Class<? extends Element> elementClass = ((GraphStep<?, ?>) steps.get(0)).getReturnClass();
    TraversalHelper.removeAllSteps(traversal);
    traversal.addStep(new TinkerCountGlobalStep<>(traversal, elementClass));
}
 
Example 5
Project: bitsy   File: MemoryGraphStore.java   View source code 6 votes vote down vote up
@Override
public <T extends Element> void createKeyIndex(String key, Class<T> elementType) {
    beginWrite();

    try {
        if (elementType == null) {
            throw new IllegalArgumentException("Element type in createKeyIndex() can not be null");
        } else if (elementType.equals(Vertex.class)) {
            vIndexMap.createKeyIndex(key, getAllVertices().iterator());
        } else if (elementType.equals(Edge.class)) {
            eIndexMap.createKeyIndex(key, getAllEdges().iterator());
        } else {
            throw new BitsyException(BitsyErrorCodes.UNSUPPORTED_INDEX_TYPE, "Encountered index type: " + elementType);
        }
    } finally {
        endWrite();
    }
}
 
Example 6
Project: bitsy   File: MemoryGraphStore.java   View source code 6 votes vote down vote up
@Override
public <T extends Element> void dropKeyIndex(String key, Class<T> elementType) {
    beginWrite();

    try {
        if (elementType == null) {
            throw new IllegalArgumentException("Element type in dropKeyIndex() can not be null");
        } else if (elementType.equals(Vertex.class)) {
            vIndexMap.dropKeyIndex(key);
        } else if (elementType.equals(Edge.class)) {
            eIndexMap.dropKeyIndex(key);
        } else {
            throw new BitsyException(BitsyErrorCodes.UNSUPPORTED_INDEX_TYPE, "Encountered index type: " + elementType);
        }
    } finally {
        endWrite();
    }
}
 
Example 7
Project: bitsy   File: MemoryGraphStore.java   View source code 6 votes vote down vote up
@Override
public <T extends Element> Set<String> getIndexedKeys(Class<T> elementType) {
    // Getting a write lock because this method accesses the list of index names which isn't thread-safe
    beginWrite();

    try {
        if (elementType == null) {
            throw new IllegalArgumentException("Element type in getIndexedKeys() can not be null");
        } else if (elementType.equals(Vertex.class)) {
            return vIndexMap.getIndexedKeys();
        } else if (elementType.equals(Edge.class)) {
            return eIndexMap.getIndexedKeys();
        } else {
            throw new BitsyException(BitsyErrorCodes.UNSUPPORTED_INDEX_TYPE, "Encountered index type: " + elementType);
        }
    } finally {
        endWrite();
    }
}
 
Example 8
Project: LiteGraph   File: ElementHelperTest.java   View source code 6 votes vote down vote up
@Test
public void shouldDeterminePropertiesAreNotEqualWhenElementsAreDifferent() {
    final Property mockPropertyA = mock(Property.class);
    final Property mockPropertyB = mock(Property.class);
    final Element mockElement = mock(Element.class);
    final Element mockElementDifferent = mock(Element.class);
    when(mockPropertyA.isPresent()).thenReturn(true);
    when(mockPropertyB.isPresent()).thenReturn(true);
    when(mockPropertyA.element()).thenReturn(mockElement);
    when(mockPropertyB.element()).thenReturn(mockElementDifferent);
    when(mockPropertyA.key()).thenReturn("k");
    when(mockPropertyB.key()).thenReturn("k");
    when(mockPropertyA.value()).thenReturn("v");
    when(mockPropertyB.value()).thenReturn("v");

    assertFalse(ElementHelper.areEqual(mockPropertyA, mockPropertyB));
}
 
Example 9
Project: grakn   File: GraqlTraversal.java   View source code 6 votes vote down vote up
private GraphTraversal<Vertex, Map<String, Element>> applyFragments(
        GraknTx graph, Set<Var> vars, ImmutableList<Fragment> fragmentList,
        GraphTraversal<Vertex, ? extends Element> traversal
) {
    Set<Var> foundVars = new HashSet<>();

    // Apply fragments in order into one single traversal
    Var currentName = null;

    for (Fragment fragment : fragmentList) {
        // Apply fragment to traversal
        fragment.applyTraversal(traversal, graph, foundVars, currentName);
        currentName = fragment.end() != null ? fragment.end() : fragment.start();
    }

    // Select all the variable names
    return selectVars(traversal, Sets.intersection(vars, foundVars));
}
 
Example 10
Project: LiteGraph   File: GraphSONSerializers.java   View source code 6 votes vote down vote up
private static void ser(final Tree tree, final JsonGenerator jsonGenerator, final TypeSerializer typeSerializer)
        throws IOException {
    jsonGenerator.writeStartObject(); 
    if (typeSerializer != null) jsonGenerator.writeStringField(GraphSONTokens.CLASS, HashMap.class.getName());
    
    Set<Map.Entry<Element, Tree>> set = tree.entrySet();
    for(Map.Entry<Element, Tree> entry : set)
    {
        jsonGenerator.writeObjectFieldStart(entry.getKey().id().toString());
        if (typeSerializer != null) jsonGenerator.writeStringField(GraphSONTokens.CLASS, HashMap.class.getName());
        jsonGenerator.writeObjectField(GraphSONTokens.KEY, entry.getKey()); 
        jsonGenerator.writeObjectField(GraphSONTokens.VALUE, entry.getValue());
        jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndObject();
}
 
Example 11
Project: LiteGraph   File: ComparatorsTest.java   View source code 6 votes vote down vote up
@Test
public void shouldSortElement() {
    final Element a = mock(Element.class);
    when(a.id()).thenReturn("Ant");
    final Element b = mock(Element.class);
    when(b.id()).thenReturn("Bat");
    final Element c = mock(Element.class);
    when(c.id()).thenReturn("Cat");

    final List<Element> l = Arrays.asList(c, b, a);
    l.sort(Comparators.ELEMENT_COMPARATOR);

    assertEquals(a.id(), l.get(0).id());
    assertEquals(b.id(), l.get(1).id());
    assertEquals(c.id(), l.get(2).id());
}
 
Example 12
Project: LiteGraph   File: ElementHelperTest.java   View source code 6 votes vote down vote up
@Test
public void shouldDeterminePropertiesAreEqual() {
    final Property mockPropertyA = mock(Property.class);
    final Property mockPropertyB = mock(Property.class);
    final Element mockElement = mock(Element.class);
    when(mockPropertyA.isPresent()).thenReturn(true);
    when(mockPropertyB.isPresent()).thenReturn(true);
    when(mockPropertyA.element()).thenReturn(mockElement);
    when(mockPropertyB.element()).thenReturn(mockElement);
    when(mockPropertyA.key()).thenReturn("k");
    when(mockPropertyB.key()).thenReturn("k");
    when(mockPropertyA.value()).thenReturn("v");
    when(mockPropertyB.value()).thenReturn("v");

    assertTrue(ElementHelper.areEqual(mockPropertyA, mockPropertyB));
}
 
Example 13
Project: LiteGraph   File: Attachable.java   View source code 6 votes vote down vote up
public static Property createProperty(final Attachable<Property> attachableProperty, final Graph hostGraph) {
    final Property baseProperty = attachableProperty.get();
    final Element baseElement = baseProperty.element();
    if (baseElement instanceof Vertex) {
        return Method.createVertexProperty((Attachable) attachableProperty, hostGraph);
    } else if (baseElement instanceof Edge) {
        final Iterator<Edge> edgeIterator = hostGraph.edges(baseElement.id());
        if (edgeIterator.hasNext())
            return edgeIterator.next().property(baseProperty.key(), baseProperty.value());
        throw new IllegalStateException("Could not find edge to create the attachable property on");
    } else { // vertex property
        final Iterator<Vertex> vertexIterator = hostGraph.vertices(((VertexProperty) baseElement).element().id());
        if (vertexIterator.hasNext()) {
            final Vertex vertex = vertexIterator.next();
            final Iterator<VertexProperty<Object>> vertexPropertyIterator = vertex.properties(((VertexProperty) baseElement).key());
            while (vertexPropertyIterator.hasNext()) {
                final VertexProperty<Object> vp = vertexPropertyIterator.next();
                if (ElementHelper.areEqual(vp, baseElement))
                    return vp.property(baseProperty.key(), baseProperty.value());
            }
        }
        throw new IllegalStateException("Could not find vertex property to create the attachable property on");
    }
}
 
Example 14
Project: LiteGraph   File: Attachable.java   View source code 6 votes vote down vote up
public static Property createProperty(final Attachable<Property> attachableProperty, final Vertex hostVertex) {
    final Property baseProperty = attachableProperty.get();
    final Element baseElement = baseProperty.element();
    if (baseElement instanceof Vertex) {
        return Method.createVertexProperty((Attachable) attachableProperty, hostVertex);
    } else if (baseElement instanceof Edge) {
        final Iterator<Edge> edgeIterator = hostVertex.edges(Direction.OUT);
        if (edgeIterator.hasNext())
            return edgeIterator.next().property(baseProperty.key(), baseProperty.value());
        throw new IllegalStateException("Could not find edge to create the property on");
    } else { // vertex property
        final Iterator<VertexProperty<Object>> vertexPropertyIterator = hostVertex.properties(((VertexProperty) baseElement).key());
        while (vertexPropertyIterator.hasNext()) {
            final VertexProperty<Object> vp = vertexPropertyIterator.next();
            if (ElementHelper.areEqual(vp, baseElement))
                return vp.property(baseProperty.key(), baseProperty.value());
        }
        throw new IllegalStateException("Could not find vertex property to create the attachable property on");
    }
}
 
Example 15
Project: gremlin-ogm   File: Page.java   View source code 5 votes vote down vote up
@Override
@SneakyThrows
public GraphTraversal<Element, Element> apply(GraphTraversal<Element, Element> traversal) {
  return traversal
      .hasLabel(org.apache.tinkerpop.gremlin.object.reflect.Label.of(elementType))
      .range(low, high);
}
 
Example 16
Project: gremlin-ogm   File: HasKeys.java   View source code 5 votes vote down vote up
@SuppressWarnings("PMD.ShortMethodName")
public static HasKeys of(org.apache.tinkerpop.gremlin.object.structure.Element element,
    Class<? extends Annotation> keyType) {
  return HasKeys.builder()
      .element(element)
      .keyType(keyType)
      .build();
}
 
Example 17
Project: gremlin-ogm   File: HasKeys.java   View source code 5 votes vote down vote up
@Override
@SneakyThrows
public GraphTraversal<Element, Element> apply(GraphTraversal<Element, Element> traversal) {
  traversal.hasLabel(element.label());
  List<Field> fields;
  if (keyType != null) {
    if (is(keyType, PrimaryKey.class)) {
      fields = primaryKeyFields(element);
    } else if (is(keyType, OrderingKey.class)) {
      fields = orderingKeyFields(element);
    } else {
      throw org.apache.tinkerpop.gremlin.object.structure.Element.Exceptions
          .invalidAnnotationType(keyType);
    }
  } else {
    fields = keyFields(element);
  }
  for (Field field : fields) {
    String key = propertyKey(field);
    Object value = propertyValue(field, element);
    if (isMissing(value)) {
      throw org.apache.tinkerpop.gremlin.object.structure.Element.Exceptions.requiredKeysMissing(
          element.getClass(), key);
    }
    traversal.has(key, value);
  }
  return traversal;
}
 
Example 18
Project: gremlin-ogm   File: UpdateBy.java   View source code 5 votes vote down vote up
@Override
public Element property(Element element, Update update) {
  if (update.getKeyValues() != null) {
    ((Vertex) element).property(update.getCardinality(),
        update.getKey(),
        update.getValue(),
        update.getKeyValues());
  } else {
    element.property(update.getKey(), update.getValue());
  }
  return element;
}
 
Example 19
Project: gremlin-ogm   File: TraversalTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() {
  sanFrancisco = City.of("San Francisco");
  traversal = (GraphTraversal<Element, O>) mock(GraphTraversal.class);
  when(traversal.property(anyString(), any())).thenReturn(traversal);
  when(traversal.hasLabel(anyString())).thenReturn(traversal);
  when(traversal.count()).thenReturn((GraphTraversal) traversal);
  g = mock(GraphTraversalSource.class);
  when(g.V()).thenReturn((GraphTraversal) traversal);
  when(g.addV(anyString())).thenReturn((GraphTraversal) traversal);
}
 
Example 20
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 5 votes vote down vote up
/**
 * Create an index for said element class ({@link Vertex} or {@link Edge}) and said property key.
 * Whenever an element has the specified key mutated, the index is updated.
 * When the index is created, all existing elements are indexed to ensure that they are captured by the index.
 *
 * @param key          the property key to index
 * @param elementClass the element class to index
 * @param <E>          The type of the element class
 */
public <E extends Element> void createIndex(final String key, final Class<E> elementClass) {
    if (Vertex.class.isAssignableFrom(elementClass)) {
        if (null == this.vertexIndex) this.vertexIndex = new TinkerIndex<>(this, TinkerVertex.class);
        this.vertexIndex.createKeyIndex(key);
    } else if (Edge.class.isAssignableFrom(elementClass)) {
        if (null == this.edgeIndex) this.edgeIndex = new TinkerIndex<>(this, TinkerEdge.class);
        this.edgeIndex.createKeyIndex(key);
    } else {
        throw new IllegalArgumentException("Class is not indexable: " + elementClass);
    }
}
 
Example 21
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 5 votes vote down vote up
/**
 * Drop the index for the specified element class ({@link Vertex} or {@link Edge}) and key.
 *
 * @param key          the property key to stop indexing
 * @param elementClass the element class of the index to drop
 * @param <E>          The type of the element class
 */
public <E extends Element> void dropIndex(final String key, final Class<E> elementClass) {
    if (Vertex.class.isAssignableFrom(elementClass)) {
        if (null != this.vertexIndex) this.vertexIndex.dropKeyIndex(key);
    } else if (Edge.class.isAssignableFrom(elementClass)) {
        if (null != this.edgeIndex) this.edgeIndex.dropKeyIndex(key);
    } else {
        throw new IllegalArgumentException("Class is not indexable: " + elementClass);
    }
}
 
Example 22
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 5 votes vote down vote up
/**
 * Return all the keys currently being index for said element class  ({@link Vertex} or {@link Edge}).
 *
 * @param elementClass the element class to get the indexed keys for
 * @param <E>          The type of the element class
 * @return the set of keys currently being indexed
 */
public <E extends Element> Set<String> getIndexedKeys(final Class<E> elementClass) {
    if (Vertex.class.isAssignableFrom(elementClass)) {
        return null == this.vertexIndex ? Collections.emptySet() : this.vertexIndex.getIndexedKeys();
    } else if (Edge.class.isAssignableFrom(elementClass)) {
        return null == this.edgeIndex ? Collections.emptySet() : this.edgeIndex.getIndexedKeys();
    } else {
        throw new IllegalArgumentException("Class is not indexable: " + elementClass);
    }
}
 
Example 23
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 5 votes vote down vote up
/**
 * Construct an {@link TinkerGraph.IdManager} from the TinkerGraph {@code Configuration}.
 */
private static IdManager<?> selectIdManager(final Configuration config, final String configKey, final Class<? extends Element> clazz) {
    final String vertexIdManagerConfigValue = config.getString(configKey, DefaultIdManager.ANY.name());
    try {
        return DefaultIdManager.valueOf(vertexIdManagerConfigValue);
    } catch (IllegalArgumentException iae) {
        try {
            return (IdManager) Class.forName(vertexIdManagerConfigValue).newInstance();
        } catch (Exception ex) {
            throw new IllegalStateException(String.format("Could not configure TinkerGraph %s id manager with %s", clazz.getSimpleName(), vertexIdManagerConfigValue));
        }
    }
}
 
Example 24
Project: tinkergraph-gremlin   File: TinkerGraphStep.java   View source code 5 votes vote down vote up
private HasContainer getIndexKey(final Class<? extends Element> indexedClass) {
    final Set<String> indexedKeys = ((TinkerGraph) this.getTraversal().getGraph().get()).getIndexedKeys(indexedClass);

    final Iterator<HasContainer> itty = IteratorUtils.filter(hasContainers.iterator(),
            c -> c.getPredicate().getBiPredicate() == Compare.eq && indexedKeys.contains(c.getKey()));
    return itty.hasNext() ? itty.next() : null;

}
 
Example 25
Project: tinkergraph-gremlin   File: TinkerGraphStep.java   View source code 5 votes vote down vote up
private <E extends Element> Iterator<E> iteratorList(final Iterator<E> iterator) {
    final List<E> list = new ArrayList<>();
    while (iterator.hasNext()) {
        final E e = iterator.next();
        if (HasContainer.testAll(e, this.hasContainers))
            list.add(e);
    }
    return list.iterator();
}
 
Example 26
Project: Ferma-OrientDB   File: OrientDBTypeResolver.java   View source code 5 votes vote down vote up
@Override
public <P extends Element, T extends Element> GraphTraversal<P, T> hasType(GraphTraversal<P, T> traverser, Class<?> type) {
	return traverser.filter(vertex -> {
		Class<?> vertexType = resolve(vertex.get());
		return vertexType == type;
	});
}
 
Example 27
Project: Ferma-OrientDB   File: OrientDBTypeResolver.java   View source code 5 votes vote down vote up
@Override
public <P extends Element, T extends Element> GraphTraversal<P, T> hasNotType(GraphTraversal<P, T> traverser, Class<?> type) {
	return traverser.filter(vertex -> {
		Class<?> vertexType = resolve(vertex.get());
		return vertexType == type;
	});
}
 
Example 28
Project: bitsy   File: BitsyElementIterator.java   View source code 5 votes vote down vote up
public BitsyElementIterator(Collection<BeanType> vertices, Iterator<ElementType> changedElemIter, Collection<ElementType> allChangedVertices) {
    this.elementIter = vertices.iterator();
    this.changedIds = null;
    this.readAhead = null;
    this.changedElemIter = changedElemIter;
    this.allChangedIds = new HashSet<UUID>();
    for (Element elem : allChangedVertices) {
        allChangedIds.add((UUID)elem.id());
    }
}
 
Example 29
Project: bitsy   File: FileBackedMemoryGraphStore.java   View source code 5 votes vote down vote up
@Override
public synchronized <T extends Element> void createKeyIndex(String key, Class<T> elementType) {
    memStore.createKeyIndex(key, elementType);
    
    // Rewrite the metadata file -- all metadata file ops are synchronized on the mA object
    synchronized (mA) {
        saveVersionAndIndexes();
    }
}
 
Example 30
Project: bitsy   File: FileBackedMemoryGraphStore.java   View source code 5 votes vote down vote up
@Override
public <T extends Element> void dropKeyIndex(String key, Class<T> elementType) {
    memStore.dropKeyIndex(key, elementType);

    // Rewrite the metadata file -- all metadata file ops are synchronized on the mA object
    synchronized (mA) {
        saveVersionAndIndexes();
    }
}
 
Example 31
Project: grakn   File: InPlaysFragment.java   View source code 5 votes vote down vote up
@Override
public GraphTraversal<Vertex, ? extends Element> applyTraversalInner(
        GraphTraversal<Vertex, ? extends Element> traversal, GraknTx graph, Collection<Var> vars) {
    GraphTraversal<Vertex, Vertex> vertexTraversal = Fragments.isVertex(traversal);
    if (required()) {
        vertexTraversal.inE(PLAYS.getLabel()).has(Schema.EdgeProperty.REQUIRED.name()).otherV();
    } else {
        vertexTraversal.in(PLAYS.getLabel());
    }

    return Fragments.inSubs(vertexTraversal);
}
 
Example 32
Project: grakn   File: IdFragment.java   View source code 5 votes vote down vote up
private GraphTraversal<Vertex, Vertex> vertexTraversal(GraphTraversal<Vertex, ? extends Element> traversal) {
    // A vertex should always be looked up by vertex property, not the actual vertex ID which may be incorrect.
    // This is because a vertex may represent a reified relation, which will use the original edge ID as an ID.
    
    // We know only vertices have this property, so the cast is safe
    //noinspection unchecked
    return (GraphTraversal<Vertex, Vertex>) traversal.has(Schema.VertexProperty.ID.name(), id().getValue());
}
 
Example 33
Project: grakn   File: Fragment.java   View source code 5 votes vote down vote up
/**
 * @param traversal the traversal to extend with this Fragment
 * @param graph     the graph to execute the traversal on
 */
public final GraphTraversal<Vertex, ? extends Element> applyTraversal(
        GraphTraversal<Vertex, ? extends Element> traversal, GraknTx graph,
        Collection<Var> vars, @Nullable Var currentVar) {
    if (currentVar != null) {
        if (!currentVar.equals(start())) {
            if (vars.contains(start())) {
                // If the variable name has been visited but the traversal is not at that variable name, select it
                traversal.select(start().name());
            } else {
                // Restart traversal when fragments are disconnected
                traversal.V().as(start().name());
            }
        }
    } else {
        // If the variable name has not been visited yet, remember it and use the 'as' step
        traversal.as(start().name());
    }

    vars.add(start());

    traversal = applyTraversalInner(traversal, graph, vars);

    Var end = end();
    if (end != null) {
        assignVar(traversal, end, vars);
    }

    vars.addAll(vars());

    return traversal;
}
 
Example 34
Project: LiteGraph   File: IoTest.java   View source code 5 votes vote down vote up
private static void assertId(final Graph g, final boolean lossyForId, final Element e, final Object expected) {
    // it is possible that a Graph (e.g. elastic-gremlin) can supportUserSuppliedIds but internally
    // represent them as a value other than Numeric (which is what's in all of the test/toy data).
    // as we feature check for userSuppliedIds when asserting the identifier, we also ensure that
    // the id can be properly asserted for that Element before attempting to do so.  By asserting
    // at this level in this way, graphs can enjoy greater test coverage in IO.
    if ((e instanceof Vertex && g.features().vertex().supportsUserSuppliedIds() && g.features().vertex().supportsNumericIds())
            || (e instanceof Edge && g.features().edge().supportsUserSuppliedIds() && g.features().edge().supportsNumericIds())
            || (e instanceof VertexProperty && g.features().vertex().properties().supportsUserSuppliedIds()) && g.features().vertex().properties().supportsNumericIds()) {
        if (lossyForId)
            assertEquals(expected.toString(), e.id().toString());
        else
            assertEquals(expected, e.id());
    }
}
 
Example 35
Project: LiteGraph   File: Parameters.java   View source code 5 votes vote down vote up
private static void legalPropertyKeyValueArray(final Object... propertyKeyValues) throws IllegalArgumentException {
    if (propertyKeyValues.length % 2 != 0)
        throw Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo();
    for (int i = 0; i < propertyKeyValues.length; i = i + 2) {
        if (!(propertyKeyValues[i] instanceof String) && !(propertyKeyValues[i] instanceof T) && !(propertyKeyValues[i] instanceof Traversal))
            throw new IllegalArgumentException("The provided key/value array must have a String, T, or Traversal on even array indices");
    }
}
 
Example 36
Project: LiteGraph   File: TinkerGraph.java   View source code 5 votes vote down vote up
/**
 * Create an index for said element class ({@link Vertex} or {@link Edge}) and said property key.
 * Whenever an element has the specified key mutated, the index is updated.
 * When the index is created, all existing elements are indexed to ensure that they are captured by the index.
 *
 * @param key          the property key to index
 * @param elementClass the element class to index
 * @param <E>          The type of the element class
 */
public <E extends Element> void createIndex(final String key, final Class<E> elementClass) {
    if (Vertex.class.isAssignableFrom(elementClass)) {
        if (null == this.vertexIndex) this.vertexIndex = new TinkerIndex<>(this, TinkerVertex.class);
        this.vertexIndex.createKeyIndex(key);
    } else if (Edge.class.isAssignableFrom(elementClass)) {
        if (null == this.edgeIndex) this.edgeIndex = new TinkerIndex<>(this, TinkerEdge.class);
        this.edgeIndex.createKeyIndex(key);
    } else {
        throw new IllegalArgumentException("Class is not indexable: " + elementClass);
    }
}
 
Example 37
Project: LiteGraph   File: ElementHelperTest.java   View source code 5 votes vote down vote up
@Test
public void shouldDetermineVerticesAreEqual() {
    final Element mockVertexA = mock(Vertex.class);
    final Element mockVertexB = mock(Vertex.class);
    when(mockVertexA.id()).thenReturn("1");
    when(mockVertexB.id()).thenReturn("1");
    assertTrue(ElementHelper.areEqual(mockVertexA, mockVertexB));
}
 
Example 38
Project: LiteGraph   File: Neo4jProperty.java   View source code 5 votes vote down vote up
public Neo4jProperty(final Element element, final String key, final V value) {
    this.element = element;
    this.key = key;
    this.value = value;
    this.graph = element instanceof Neo4jVertexProperty ?
            ((Neo4jVertex) (((Neo4jVertexProperty) element).element())).graph :
            ((Neo4jElement) element).graph;
}
 
Example 39
Project: grakn   File: OutRolePlayerFragment.java   View source code 5 votes vote down vote up
@Override
public GraphTraversal<Vertex, ? extends Element> applyTraversalInner(
        GraphTraversal<Vertex, ? extends Element> traversal, GraknTx graph, Collection<Var> vars) {

    return Fragments.union(traversal, ImmutableSet.of(
            reifiedRelationTraversal(graph, vars),
            edgeRelationTraversal(graph, Direction.OUT, RELATIONSHIP_ROLE_OWNER_LABEL_ID, vars),
            edgeRelationTraversal(graph, Direction.IN, RELATIONSHIP_ROLE_VALUE_LABEL_ID, vars)
    ));
}
 
Example 40
Project: grakn   File: InRolePlayerFragment.java   View source code 5 votes vote down vote up
@Override
public GraphTraversal<Vertex, ? extends Element> applyTraversalInner(
        GraphTraversal<Vertex, ? extends Element> traversal, GraknTx graph, Collection<Var> vars) {

    return Fragments.union(Fragments.isVertex(traversal), ImmutableSet.of(
            reifiedRelationTraversal(graph, vars),
            edgeRelationTraversal(graph, Direction.OUT, RELATIONSHIP_ROLE_OWNER_LABEL_ID, vars),
            edgeRelationTraversal(graph, Direction.IN, RELATIONSHIP_ROLE_VALUE_LABEL_ID, vars)
    ));
}