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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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)
    ));
}
 
Example 41
Project: grakn   File: LabelFragment.java   Source Code and License 5 votes vote down vote up
@Override
public GraphTraversal<Vertex, ? extends Element> applyTraversalInner(
        GraphTraversal<Vertex, ? extends Element> traversal, GraknTx graph, Collection<Var> vars) {

    Set<Integer> labelIds =
            labels().stream().map(label -> graph.admin().convertToId(label).getValue()).collect(toSet());

    if (labelIds.size() == 1) {
        int labelId = Iterables.getOnlyElement(labelIds);
        return traversal.has(LABEL_ID.name(), labelId);
    } else {
        return traversal.has(LABEL_ID.name(), P.within(labelIds));
    }
}
 
Example 42
Project: LiteGraph   File: HasTest.java   Source Code and License 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXage_gt_30X() {
    final Traversal<Vertex, Vertex> traversal = get_g_V_hasXage_gt_30X();
    printTraversalForm(traversal);
    final List<Vertex> list = traversal.toList();
    assertEquals(2, list.size());
    for (final Element v : list) {
        assertTrue(v.<Integer>value("age") > 30);
    }
}
 
Example 43
Project: grakn   File: GraqlTraversal.java   Source Code and License 5 votes vote down vote up
/**
 * @return a gremlin traversal that represents this inner query
 */
private GraphTraversal<Vertex, Map<String, Element>> getConjunctionTraversal(
        GraknTx graph, GraphTraversal<Vertex, Vertex> traversal, Set<Var> vars, ImmutableList<Fragment> fragmentList
) {
    GraphTraversal<Vertex, ? extends Element> newTraversal = traversal;

    // If the first fragment can operate on edges, then we have to navigate all edges as well
    if (fragmentList.get(0).canOperateOnEdges()) {
        newTraversal = traversal.union(__.identity(), __.outE(Schema.EdgeLabel.ATTRIBUTE.getLabel()));
    }

    return applyFragments(graph, vars, fragmentList, newTraversal);
}
 
Example 44
Project: grakn   File: MatchBase.java   Source Code and License 5 votes vote down vote up
/**
 * @param commonVars set of variables of interest
 * @param graph the graph to get results from
 * @param graqlTraversal gral traversal corresponding to the provided pattern
 * @return resulting answer stream
 */
public static Stream<Answer> streamWithTraversal(Set<Var> commonVars, GraknTx graph, GraqlTraversal graqlTraversal) {
    Set<Var> vars = Sets.filter(commonVars, Var::isUserDefinedName);

    GraphTraversal<Vertex, Map<String, Element>> traversal = graqlTraversal.getGraphTraversal(graph, vars);

    return traversal.toStream()
            .map(elements -> makeResults(vars, graph, elements))
            .flatMap(CommonUtil::optionalToStream)
            .distinct()
            .sequential()
            .map(QueryAnswer::new);
}
 
Example 45
Project: grakn   File: MatchBase.java   Source Code and License 5 votes vote down vote up
/**
 * @param vars set of variables of interest
 * @param graph the graph to get results from
 * @param elements a map of vertices and edges where the key is the variable name
 * @return a map of concepts where the key is the variable name
 */
private static Optional<Map<Var, Concept>> makeResults(Set<Var> vars, GraknTx graph, Map<String, Element> elements) {
    Map<Var, Concept> map = new HashMap<>();
    for (Var var : vars) {
        Element element = elements.get(var.name());
        if (element == null) {
            throw GraqlQueryException.unexpectedResult(var);
        } else {
            Concept concept = buildConcept(graph.admin(), element);
            map.put(var, concept);
        }
    }

    return Optional.of(map);
}
 
Example 46
Project: LiteGraph   File: TinkerGraphStep.java   Source Code and License 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 47
Project: LiteGraph   File: PartitionStrategyTraverseTest.java   Source Code and License 5 votes vote down vote up
public static GraphTraversal create(final Class<? extends Element> clazz) {
    final Graph mockedGraph = mock(Graph.class);
    final Graph.Features features = mock(Graph.Features.class);
    final Graph.Features.VertexFeatures vertexFeatures = mock(Graph.Features.VertexFeatures.class);
    when(mockedGraph.features()).thenReturn(features);
    when(features.vertex()).thenReturn(vertexFeatures);
    when(vertexFeatures.getCardinality(any())).thenReturn(VertexProperty.Cardinality.single);
    final DefaultGraphTraversal t = new DefaultGraphTraversal<>(mockedGraph);
    if (clazz != null) t.asAdmin().addStep(new GraphStep<>(t.asAdmin(), clazz, true));
    return t;
}
 
Example 48
Project: LiteGraph   File: ReferenceFactory.java   Source Code and License 5 votes vote down vote up
public static <D> D detach(final Object object) {
    if (object instanceof Element) {
        return (D) ReferenceFactory.detach((Element) object);
    } else if (object instanceof Property) {
        return (D) ReferenceFactory.detach((Property) object);
    } else if (object instanceof Path) {
        return (D) ReferenceFactory.detach((Path) object);
    } else {
        return (D) object;
    }
}
 
Example 49
Project: LiteGraph   File: TinkerGraph.java   Source Code and License 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 50
Project: LiteGraph   File: TinkerGraphStep.java   Source Code and License 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 51
Project: LiteGraph   File: ElementHelperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldNotAllowEvenNumberOfKeyValuesAndInvalidKeys() {
    try {
        ElementHelper.legalPropertyKeyValueArray("aKey", "test", "value-for-this-one", 1, 1, "none");
        fail("Should fail as there is an even number of key-values, but a bad key");
    } catch (IllegalArgumentException iae) {
        assertEquals(Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices().getMessage(), iae.getMessage());
    }
}
 
Example 52
Project: LiteGraph   File: DriverRemoteConnection.java   Source Code and License 5 votes vote down vote up
@Override
public Traverser.Admin<E> next() {
    final Traverser.Admin<E> traverser = super.next();
    if (traverser.get() instanceof Attachable && !(traverser.get() instanceof Property))
        traverser.set((E) ((Attachable<Element>) traverser.get()).attach(Attachable.Method.get(graph)));
    return traverser;
}
 
Example 53
Project: LiteGraph   File: ResultTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldGetVertex() {
    final Vertex v = g.vertices(1).next();
    final Result result = new Result(v);

    assertEquals(v, result.getVertex());
    assertEquals(v, result.get(Vertex.class));
    assertEquals(v, result.getElement());
    assertEquals(v, result.get(Element.class));
}
 
Example 54
Project: LiteGraph   File: ResultTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldGetVertexProperty() {
    final VertexProperty<String> v = g.vertices(1).next().property("name");
    final Result result = new Result(v);

    assertEquals(v, result.getVertexProperty());
    assertEquals(v, result.get(VertexProperty.class));
    assertEquals(v, result.getElement());
    assertEquals(v, result.get(Element.class));
}
 
Example 55
Project: LiteGraph   File: ReferenceFactory.java   Source Code and License 5 votes vote down vote up
public static ReferenceElement detach(final Element element) {
    if (element instanceof Vertex)
        return detach((Vertex) element);
    else if (element instanceof Edge)
        return detach((Edge) element);
    else if (element instanceof VertexProperty)
        return detach((VertexProperty) element);
    else
        throw new IllegalArgumentException("The provided argument is an unknown element: " + element + ':' + element.getClass());
}
 
Example 56
Project: LiteGraph   File: ElementHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Determine whether an array of ids are either all elements or ids of elements. This is typically used as a pre-condition check.
 *
 * @param clazz the class of the element for which the ids will bind
 * @param ids   the ids that must be either elements or id objects, else
 *              {@link org.apache.tinkerpop.gremlin.structure.Graph.Exceptions#idArgsMustBeEitherIdOrElement()} is thrown.
 */
public static void validateMixedElementIds(final Class<? extends Element> clazz, final Object... ids) throws IllegalArgumentException {
    if (ids.length > 1) {
        final boolean element = clazz.isAssignableFrom(ids[0].getClass());
        for (int i = 1; i < ids.length; i++) {
            if (clazz.isAssignableFrom(ids[i].getClass()) != element)
                throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
        }
    }
}
 
Example 57
Project: LiteGraph   File: ElementHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Determines whether a list of key/values are legal, ensuring that there are an even number of values submitted
 * and that the key values in the list of arguments are {@link String} or {@link org.apache.tinkerpop.gremlin.structure.Element} objects.
 *
 * @param propertyKeyValues a list of key/value pairs
 * @throws IllegalArgumentException if something in the pairs is illegal
 */
public 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))
            throw Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices();
    }
}
 
Example 58
Project: LiteGraph   File: ComputerResultStep.java   Source Code and License 5 votes vote down vote up
public Iterator<Traverser.Admin<S>> attach(final Iterator<Traverser.Admin<S>> iterator, final Graph graph) {
    return IteratorUtils.map(iterator, traverser -> {
        traverser.setSideEffects(this.getTraversal().getSideEffects());   // necessary to ensure no NPE
        if (this.attachElements && (traverser.get() instanceof Attachable) && !(traverser.get() instanceof Property))
            traverser.set((S) ((Attachable<Element>) traverser.get()).attach(Attachable.Method.get(graph)));
        return traverser;
    });
}
 
Example 59
Project: LiteGraph   File: ElementHelper.java   Source Code and License 5 votes vote down vote up
/**
 * A standard method for determining if two {@link org.apache.tinkerpop.gremlin.structure.Element} objects are equal. This method should be used by any
 * {@link Object#equals(Object)} implementation to ensure consistent behavior. This method is used for Vertex, Edge, and VertexProperty.
 *
 * @param a The first {@link org.apache.tinkerpop.gremlin.structure.Element}
 * @param b The second {@link org.apache.tinkerpop.gremlin.structure.Element} (as an {@link Object})
 * @return true if elements and equal and false otherwise
 */
public static boolean areEqual(final Element a, final Object b) {
    if (null == b || null == a)
        return false;

    if (a == b)
        return true;
    if (!((a instanceof Vertex && b instanceof Vertex) ||
            (a instanceof Edge && b instanceof Edge) ||
            (a instanceof VertexProperty && b instanceof VertexProperty)))
        return false;
    return haveEqualIds(a, (Element) b);
}
 
Example 60
Project: LiteGraph   File: HasTest.java   Source Code and License 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXage_isXgt_30XX() {
    final Traversal<Vertex, Vertex> traversal = get_g_V_hasXage_isXgt_30XX();
    printTraversalForm(traversal);
    final List<Vertex> list = traversal.toList();
    assertEquals(2, list.size());
    for (final Element v : list) {
        assertTrue(v.<Integer>value("age") > 30);
    }
}