org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil. 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: MathStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Double map(final Traverser.Admin<S> traverser) {
    final Expression localExpression = new Expression(this.expression.getExpression());
    for (final String var : this.expression.getVariables()) {
        final Object o = var.equals(CURRENT) ?
                TraversalUtil.applyNullable(traverser, this.traversalRing.next()) :
                TraversalUtil.applyNullable((S) this.getNullableScopeValue(Pop.last, var, traverser), this.traversalRing.next());

        // it's possible for ElementValueTraversal to return null or something that is possibly not a Number.
        // worth a check to try to return a nice error message. The TraversalRing<S, Number> is a bit optimistic
        // given type erasure. It could easily end up otherwise.
        if (!(o instanceof Number))
            throw new IllegalStateException(String.format(
                    "The variable %s for math() step must resolve to a Number - it is instead of type %s with value %s",
                    var, Objects.isNull(o) ? "null" : o.getClass().getName(), o));

        localExpression.setVariable(var, ((Number) o).doubleValue());
    }
    this.traversalRing.reset();
    return localExpression.evaluate();
}
 
Example #2
Source File: PixyCoalesceStep.java    From pixy with Apache License 2.0 6 votes vote down vote up
@Override
    protected Object map(final Traverser.Admin traverser) {
        final Map<String, Object> bindings = new LinkedHashMap<>(this.selectKeys.size(), 1.0f);
        for (final String selectKey : this.selectKeys) {
            final Object end = this.getNullableScopeValue(null, selectKey, traverser);
            if (null != end) {
                bindings.put(selectKey, TraversalUtil.applyNullable(end, this.traversalRing.next()));
            }

// Commented out of SelectStep by sridhar
//            else {
//                this.traversalRing.reset();
//                return null;
//            }
        }
        this.traversalRing.reset();

		for (String stepName : selectKeys) {
			Object ans = bindings.get(stepName);
			if (ans != null) {
				return ans;
			}
		}

		throw new PixyException(PixyErrorCodes.COALESCE_FAILURE, "Unable to find locate any of the named steps: " + selectKeys);
    }
 
Example #3
Source File: BranchStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Choose the right traversal option to apply and seed those options with this traverser.
 */
private void applyCurrentTraverser(final Traverser.Admin<S> start) {
    // first get the value of the choice based on the current traverser and use that to select the right traversal
    // option to which that traverser should be routed
    final Object choice = TraversalUtil.apply(start, this.branchTraversal);
    final List<Traversal.Admin<S, E>> branches = pickBranches(choice);

    // if a branch is identified, then split the traverser and add it to the start of the option so that when
    // that option is iterated (in the calling method) that value can be applied.
    if (null != branches)
        branches.forEach(traversal -> traversal.addStart(start.split()));

    if (choice != Pick.any) {
        final List<Traversal.Admin<S, E>> anyBranch = this.traversalPickOptions.get(Pick.any);
        if (null != anyBranch)
            anyBranch.forEach(traversal -> traversal.addStart(start.split()));
    }
}
 
Example #4
Source File: GroupSideEffectStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected void sideEffect(final Traverser.Admin<S> traverser) {
    final Map<K, V> map = new HashMap<>(1);
    this.valueTraversal.reset();
    this.valueTraversal.addStart(traverser);

    // reset the barrierStep as there are now ProfileStep instances present and the timers won't start right
    // without specific configuration through wrapping both the Barrier and ProfileStep in ProfiledBarrier
    if (resetBarrierForProfiling) {
        barrierStep = determineBarrierStep(valueTraversal);

        // the barrier only needs to be reset once
        resetBarrierForProfiling = false;
    }

    if (null == this.barrierStep) {
        if (this.valueTraversal.hasNext())
            map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.valueTraversal.next());
    } else if (this.barrierStep.hasNextBarrier())
        map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.barrierStep.nextBarrier());
    if (!map.isEmpty())
        this.getTraversal().getSideEffects().add(this.sideEffectKey, map);
}
 
Example #5
Source File: SelectStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Traverser.Admin<Map<String, E>> processNextStart() throws NoSuchElementException {
    final Traverser.Admin<S> traverser = this.starts.next();
    final Map<String, E> bindings = new LinkedHashMap<>(this.selectKeys.size(), 1.0f);
    try {
        for (final String selectKey : this.selectKeys) {
            final E end = this.getScopeValue(this.pop, selectKey, traverser);
            bindings.put(selectKey, TraversalUtil.applyNullable(end, this.traversalRing.next()));
        }
    } catch (KeyNotFoundException nfe) {
        return EmptyTraverser.instance();
    } finally {
        this.traversalRing.reset();
    }

    return PathProcessor.processTraverserPathLabels(traverser.split(bindings, this), this.keepLabels);
}
 
Example #6
Source File: ValueTraversal.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public void addStart(final Traverser.Admin<T> start) {
    if (null == this.bypassTraversal) {
        final T o = start.get();
        if (o instanceof Element)
            this.value = (V)((Element) o).property(propertyKey).orElse(null);
        else if (o instanceof Map)
            this.value = (V) ((Map) o).get(propertyKey);
        else
            throw new IllegalStateException(String.format(
                    "The by(\"%s\") modulator can only be applied to a traverser that is an Element or a Map - it is being applied to [%s] a %s class instead",
                    propertyKey, o, o.getClass().getSimpleName()));
    } else {
        this.value = TraversalUtil.apply(start, this.bypassTraversal);
    }
}
 
Example #7
Source File: TraversalSelectStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Traverser.Admin<E> processNextStart() {
    final Traverser.Admin<S> traverser = this.starts.next();
    final Iterator<E> keyIterator = TraversalUtil.applyAll(traverser, this.keyTraversal);
    if (keyIterator.hasNext()) {
        final E key = keyIterator.next();
        try {
            final E end = getScopeValue(pop, key, traverser);
            final Traverser.Admin<E> outTraverser = traverser.split(null == end ? null : TraversalUtil.applyNullable(end, this.selectTraversal), this);
            if (!(this.getTraversal().getParent() instanceof MatchStep)) {
                PathProcessor.processTraverserPathLabels(outTraverser, this.keepLabels);
            }
            return outTraverser;
        } catch (KeyNotFoundException nfe) {
            return EmptyTraverser.instance();
        }
    } else {
        return EmptyTraverser.instance();
    }
}
 
Example #8
Source File: GroupStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Map<K, V> projectTraverser(final Traverser.Admin<S> traverser) {
    final Map<K, V> map = new HashMap<>(1);
    this.valueTraversal.reset();
    this.valueTraversal.addStart(traverser);

    // reset the barrierStep as there are now ProfileStep instances present and the timers won't start right
    // without specific configuration through wrapping both the Barrier and ProfileStep in ProfiledBarrier
    if (resetBarrierForProfiling) {
        barrierStep = determineBarrierStep(valueTraversal);

        // the barrier only needs to be reset once
        resetBarrierForProfiling = false;
    }

    if (null == this.barrierStep) {
        if (this.valueTraversal.hasNext())
            map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.valueTraversal.next());
    } else if (this.barrierStep.hasNextBarrier())
        map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.barrierStep.nextBarrier());
    return map;
}
 
Example #9
Source File: OrStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    for (final Traversal.Admin<S, ?> traversal : this.traversals) {
        if (TraversalUtil.test(traverser, traversal))
            return true;
    }
    return false;
}
 
Example #10
Source File: SqlgAndStepBarrier.java    From sqlg with MIT License 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    for (final Traversal.Admin<S, ?> traversal : this.traversals) {
        if (TraversalUtil.test(traverser, traversal))
            return true;
    }
    return false;
}
 
Example #11
Source File: SqlgOrStepBarrier.java    From sqlg with MIT License 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    for (final Traversal.Admin<S, ?> traversal : this.traversals) {
        if (TraversalUtil.test(traverser, traversal))
            return true;
    }
    return false;
}
 
Example #12
Source File: ChainedComparator.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(final S objectA, final S objectB) {
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        final int comparison = this.traversers ?
                pair.getValue1().compare(TraversalUtil.apply((Traverser.Admin<S>) objectA, pair.getValue0()), TraversalUtil.apply((Traverser.Admin<S>) objectB, pair.getValue0())) :
                pair.getValue1().compare(TraversalUtil.apply(objectA, pair.getValue0()), TraversalUtil.apply(objectB, pair.getValue0()));
        if (comparison != 0)
            return comparison;
    }
    return 0;
}
 
Example #13
Source File: PageRankVertexProgram.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final Vertex vertex, Messenger<Double> messenger, final Memory memory) {
    if (memory.isInitialIteration()) {
        messenger.sendMessage(this.countMessageScope, 1.0d);
        memory.add(VERTEX_COUNT, 1.0d);
    } else {
        final double vertexCount = memory.<Double>get(VERTEX_COUNT);
        final double edgeCount;
        double pageRank;
        if (1 == memory.getIteration()) {
            edgeCount = IteratorUtils.reduce(messenger.receiveMessages(), 0.0d, (a, b) -> a + b);
            vertex.property(VertexProperty.Cardinality.single, EDGE_COUNT, edgeCount);
            pageRank = null == this.initialRankTraversal ?
                    0.0d :
                    TraversalUtil.apply(vertex, this.initialRankTraversal.get()).doubleValue();
        } else {
            edgeCount = vertex.value(EDGE_COUNT);
            pageRank = IteratorUtils.reduce(messenger.receiveMessages(), 0.0d, (a, b) -> a + b);
        }
        //////////////////////////
        final double teleporationEnergy = memory.get(TELEPORTATION_ENERGY);
        if (teleporationEnergy > 0.0d) {
            final double localTerminalEnergy = teleporationEnergy / vertexCount;
            pageRank = pageRank + localTerminalEnergy;
            memory.add(TELEPORTATION_ENERGY, -localTerminalEnergy);
        }
        final double previousPageRank = vertex.<Double>property(this.property).orElse(0.0d);
        memory.add(CONVERGENCE_ERROR, Math.abs(pageRank - previousPageRank));
        vertex.property(VertexProperty.Cardinality.single, this.property, pageRank);
        memory.add(TELEPORTATION_ENERGY, (1.0d - this.alpha) * pageRank);
        pageRank = this.alpha * pageRank;
        if (edgeCount > 0.0d)
            messenger.sendMessage(this.incidentMessageScope, pageRank / edgeCount);
        else
            memory.add(TELEPORTATION_ENERGY, pageRank);
    }
}
 
Example #14
Source File: BranchStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private List<Traversal.Admin<S, E>> pickBranches(final Object choice) {
    final List<Traversal.Admin<S, E>> branches = new ArrayList<>();
    if (choice instanceof Pick) {
        if (this.traversalPickOptions.containsKey(choice)) {
            branches.addAll(this.traversalPickOptions.get(choice));
        }
    }
    for (final Pair<Traversal.Admin, Traversal.Admin<S, E>> p : this.traversalOptions) {
        if (TraversalUtil.test(choice, p.getValue0())) {
            branches.add(p.getValue1());
        }
    }
    return branches.isEmpty() ? this.traversalPickOptions.get(Pick.none) : branches;
}
 
Example #15
Source File: DedupGlobalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Object, Traverser.Admin<S>> nextBarrier() throws NoSuchElementException {
    final Map<Object, Traverser.Admin<S>> map = null != this.barrier ? this.barrier : new HashMap<>();
    while (this.starts.hasNext()) {
        final Traverser.Admin<S> traverser = this.starts.next();
        final Object object;
        if (null != this.dedupLabels) {
            object = new ArrayList<>(this.dedupLabels.size());
            for (final String label : this.dedupLabels) {
                ((List) object).add(TraversalUtil.applyNullable((S) this.getSafeScopeValue(Pop.last, label, traverser), this.dedupTraversal));
            }
        } else {
            object = TraversalUtil.applyNullable(traverser, this.dedupTraversal);
        }
        if (!map.containsKey(object)) {
            traverser.setBulk(1L);

            // DetachedProperty and DetachedVertexProperty both have a transient for the Host element. that causes
            // trouble for olap which ends up requiring the Host later. can't change the transient without some
            // consequences: (1) we break gryo formatting and io tests start failing (2) storing the element with
            // the property has the potential to bloat detached Element instances as it basically stores that data
            // twice. Not sure if it's smart to change that at least in 3.4.x and not without some considerable
            // thought as to what might be major changes. To work around the problem we will detach properties as
            // references so that the parent element goes with it. Also, given TINKERPOP-2318 property comparisons
            // have changed in such a way that allows this to work properly
            if (traverser.get() instanceof Property)
                traverser.set(ReferenceFactory.detach(traverser.get()));
            else
                traverser.set(DetachedFactory.detach(traverser.get(), true));
            map.put(object, traverser);
        }
    }
    this.barrier = null;
    this.barrierIterator = null;
    if (map.isEmpty())
        throw FastNoSuchElementException.instance();
    else
        return map;
}
 
Example #16
Source File: DedupGlobalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    if (this.onGraphComputer && !this.executingAtMaster) return true;
    traverser.setBulk(1L);
    if (null == this.dedupLabels) {
        return this.duplicateSet.add(TraversalUtil.applyNullable(traverser, this.dedupTraversal));
    } else {
        final List<Object> objects = new ArrayList<>(this.dedupLabels.size());
        this.dedupLabels.forEach(label -> objects.add(TraversalUtil.applyNullable((S) this.getSafeScopeValue(Pop.last, label, traverser), this.dedupTraversal)));
        return this.duplicateSet.add(objects);
    }
}
 
Example #17
Source File: AndStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    for (final Traversal.Admin<S, ?> traversal : this.traversals) {
        if (!TraversalUtil.test(traverser, traversal))
            return false;
    }
    return true;
}
 
Example #18
Source File: PathFilterStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    final Path path = traverser.path().subPath(this.fromLabel, this.toLabel);
    if (this.traversalRing.isEmpty())
        return path.isSimple() == this.isSimple;
    else {
        this.traversalRing.reset();
        final Path byPath = MutablePath.make();
        path.forEach((object, labels) -> byPath.extend(TraversalUtil.applyNullable(object, this.traversalRing.next()), labels));
        return byPath.isSimple() == this.isSimple;
    }
}
 
Example #19
Source File: WherePredicateStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    final Object value = null == this.startKey ?
            TraversalUtil.applyNullable(traverser, this.traversalRing.next()) :
            TraversalUtil.applyNullable((S) this.getSafeScopeValue(Pop.last, this.startKey, traverser), this.traversalRing.next());
    this.setPredicateValues(this.predicate, traverser, this.selectKeys.iterator());
    this.traversalRing.reset();
    return this.predicate.test(value);
}
 
Example #20
Source File: OrderGlobalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private final ProjectedTraverser<S, Object> createProjectedTraverser(final Traverser.Admin<S> traverser) {
    // this was ProjectedTraverser<S, C> but the projection may not be C in the case of a lambda where a
    // Comparable may not be expected but rather an object that can be compared in any way given a lambda.
    // not sure why this is suddenly an issue but Intellij would not let certain tests pass without this
    // adjustment here.
    final List<Object> projections = new ArrayList<>(this.comparators.size());
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        projections.add(TraversalUtil.apply(traverser, pair.getValue0()));
    }
    return new ProjectedTraverser<>(traverser, projections);
}
 
Example #21
Source File: Parameters.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the list of values for a key, while resolving the values of any parameters that are {@link Traversal}
 * objects.
 */
public <S, E> List<E> get(final Traverser.Admin<S> traverser, final Object key, final Supplier<E> defaultValue) {
    final List<E> values = (List<E>) this.parameters.get(key);
    if (null == values) return Collections.singletonList(defaultValue.get());
    final List<E> result = new ArrayList<>();
    for (final Object value : values) {
        result.add(value instanceof Traversal.Admin ? TraversalUtil.apply(traverser, (Traversal.Admin<S, E>) value) : (E) value);
    }
    return result;
}
 
Example #22
Source File: AggregateGlobalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void processAllStarts() {
    if (this.starts.hasNext()) {
        final BulkSet<Object> bulkSet = new BulkSet<>();
        while (this.starts.hasNext()) {
            final Traverser.Admin<S> traverser = this.starts.next();
            bulkSet.add(TraversalUtil.applyNullable(traverser, this.aggregateTraversal), traverser.bulk());
            traverser.setStepId(this.getNextStep().getId()); // when barrier is reloaded, the traversers should be at the next step
            this.barrier.add(traverser);
        }
        this.getTraversal().getSideEffects().add(this.sideEffectKey, bulkSet);
    }
}
 
Example #23
Source File: SelectOneStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<E> processNextStart() throws NoSuchElementException {
    final Traverser.Admin<S> traverser = this.starts.next();

    try {
        final S o = getScopeValue(pop, selectKey, traverser);
        if (null == o) return traverser.split(null, this);
        final Traverser.Admin<E> outTraverser = traverser.split(TraversalUtil.applyNullable(o, this.selectTraversal), this);
        if (!(this.getTraversal().getParent() instanceof MatchStep))
            PathProcessor.processTraverserPathLabels(outTraverser, this.keepLabels);
        return outTraverser;
    } catch (KeyNotFoundException nfe) {
        return EmptyTraverser.instance();
    }
}
 
Example #24
Source File: ProjectStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, E> map(final Traverser.Admin<S> traverser) {
    final Map<String, E> end = new LinkedHashMap<>(this.projectKeys.size(), 1.0f);
    for (final String projectKey : this.projectKeys) {
        end.put(projectKey, TraversalUtil.applyNullable(traverser, this.traversalRing.next()));
    }
    this.traversalRing.reset();
    return end;
}
 
Example #25
Source File: Parameters.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the array of keys/values of the parameters while resolving parameter values that contain
 * {@link Traversal} instances.
 */
public <S> Object[] getKeyValues(final Traverser.Admin<S> traverser, final Object... exceptKeys) {
    if (this.parameters.isEmpty()) return EMPTY_ARRAY;
    final List<Object> keyValues = new ArrayList<>();
    for (final Map.Entry<Object, List<Object>> entry : this.parameters.entrySet()) {
        if (!ArrayUtils.contains(exceptKeys, entry.getKey())) {
            for (final Object value : entry.getValue()) {
                keyValues.add(entry.getKey() instanceof Traversal.Admin ? TraversalUtil.apply(traverser, (Traversal.Admin<S, ?>) entry.getKey()) : entry.getKey());
                keyValues.add(value instanceof Traversal.Admin ? TraversalUtil.apply(traverser, (Traversal.Admin<S, ?>) value) : value);
            }
        }
    }
    return keyValues.toArray(new Object[keyValues.size()]);
}
 
Example #26
Source File: PathStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Path map(final Traverser.Admin<S> traverser) {
    final Path path = traverser.path().subPath(this.fromLabel, this.toLabel);
    if (this.traversalRing.isEmpty())
        return path;
    else {
        this.traversalRing.reset();
        final Path byPath = MutablePath.make();
        path.forEach((object, labels) -> byPath.extend(TraversalUtil.applyNullable(object, this.traversalRing.next()), labels));
        return byPath;
    }
}
 
Example #27
Source File: GroupCountStep.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Map<E, Long> projectTraverser(final Traverser.Admin<S> traverser) {
    final Map<E, Long> map = new HashMap<>(1);
    map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), traverser.bulk());
    return map;
}
 
Example #28
Source File: TraversalFlatMapStep.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
protected Iterator<E> flatMap(final Traverser.Admin<S> traverser) {
    return TraversalUtil.applyAll(traverser, this.flatMapTraversal);
}
 
Example #29
Source File: SqlgRepeatStepBarrier.java    From sqlg with MIT License 4 votes vote down vote up
private boolean doEmit(final Traverser.Admin<S> traverser, boolean emitFirst) {
    return emitFirst == this.emitFirst && null != this.emitTraversal && TraversalUtil.test(traverser, this.emitTraversal);
}
 
Example #30
Source File: SqlgRepeatStepBarrier.java    From sqlg with MIT License 4 votes vote down vote up
private boolean doUntil(final Traverser.Admin<S> traverser, boolean utilFirst) {
    return utilFirst == this.untilFirst && null != this.untilTraversal && TraversalUtil.test(traverser, this.untilTraversal);
}