org.apache.tinkerpop.gremlin.process.traversal.step.filter.WherePredicateStep Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.step.filter.WherePredicateStep. 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: MatchStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> getScopeKeys() {
    if (null == this.scopeKeys) { // computer the first time and then save resultant keys
        this.scopeKeys = new HashSet<>();
        if (null != this.selectKey)
            this.scopeKeys.add(this.selectKey);
        final Set<String> endLabels = ((MatchStep<?, ?>) this.getTraversal().getParent()).getMatchEndLabels();
        TraversalHelper.anyStepRecursively(step -> {
            if (step instanceof WherePredicateStep || step instanceof WhereTraversalStep) {
                for (final String key : ((Scoping) step).getScopeKeys()) {
                    if (endLabels.contains(key)) this.scopeKeys.add(key);
                }
            }
            return false;
        }, this.getTraversal());
        // this is the old way but it only checked for where() as the next step, not arbitrarily throughout traversal
        // just going to keep this in case something pops up in the future and this is needed as an original reference.
        /* if (this.getNextStep() instanceof WhereTraversalStep || this.getNextStep() instanceof WherePredicateStep)
           this.scopeKeys.addAll(((Scoping) this.getNextStep()).getScopeKeys());*/
        this.scopeKeys = Collections.unmodifiableSet(this.scopeKeys);
    }
    return this.scopeKeys;
}
 
Example #2
Source File: MatchStepTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreCompilationOfWherePredicate() {
    final List<Traversal.Admin<?, ?>> traversals = Arrays.asList(
            __.match(as("a").out().as("b"), as("c").where(P.neq("d"))).asAdmin(),
            __.match(as("a").out().as("b"), where("c", P.neq("d"))).asAdmin());
    assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal
    traversals.forEach(traversal -> {
        final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep();
        //assertFalse(matchStep.getStartLabel().isPresent());
        assertEquals(2, matchStep.getGlobalChildren().size());
        Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0);
        assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get());
        assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass());
        assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get());
        //
        pattern = matchStep.getGlobalChildren().get(1);
        assertEquals(MatchStep.MatchStartStep.class, pattern.getStartStep().getClass());
        assertEquals("c", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get());
        assertEquals(WherePredicateStep.class, pattern.getStartStep().getNextStep().getClass());
        assertEquals(MatchStep.MatchEndStep.class, pattern.getStartStep().getNextStep().getNextStep().getClass());
        assertFalse(((WherePredicateStep<?>) pattern.getStartStep().getNextStep()).getStartKey().isPresent());
        assertEquals("d", ((WherePredicateStep<?>) pattern.getStartStep().getNextStep()).getPredicate().get().getOriginalValue());
    });
}
 
Example #3
Source File: JanusPreviousPropertyStepStrategy.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void apply(Traversal.Admin<?, ?> traversal) {

    // Retrieve all graph (`V()`) steps - this is the step the strategy should replace
    List<GraphStep> graphSteps = TraversalHelper.getStepsOfAssignableClass(GraphStep.class, traversal);

    for (GraphStep graphStep : graphSteps) {
        // For each graph step, confirm it follows this pattern:
        // `V().filter(__.properties(a).where(P.eq(b)))`

        if (!(graphStep.getNextStep() instanceof TraversalFilterStep)) continue;
        TraversalFilterStep<Vertex> filterStep = (TraversalFilterStep<Vertex>) graphStep.getNextStep();

        // Retrieve the filter steps e.g. `__.properties(a).where(P.eq(b))`
        List<Step> steps = stepsFromFilterStep(filterStep);

        if (steps.size() < 2) continue;
        Step propertiesStep = steps.get(0); // This is `properties(a)`
        Step whereStep = steps.get(1);      // This is `filter(__.where(P.eq(b)))`

        // Get the property key `a`
        if (!(propertiesStep instanceof PropertiesStep)) continue;
        Optional<String> propertyKey = propertyFromPropertiesStep((PropertiesStep<Vertex>) propertiesStep);
        if (!propertyKey.isPresent()) continue;

        // Get the step label `b`
        if (!(whereStep instanceof WherePredicateStep)) continue;
        Optional<String> label = labelFromWhereEqPredicate((WherePredicateStep<Vertex>) whereStep);
        if (!label.isPresent()) continue;

        executeStrategy(traversal, graphStep, filterStep, propertyKey.get(), label.get());
    }
}
 
Example #4
Source File: JanusPreviousPropertyStepStrategy.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private Optional<String> labelFromWhereEqPredicate(WherePredicateStep<Vertex> whereStep) {
    Optional<P<?>> optionalPredicate = whereStep.getPredicate();

    return optionalPredicate.flatMap(predicate -> {
        if (!predicate.getBiPredicate().equals(Compare.eq)) return Optional.empty();
        return Optional.of((String) predicate.getValue());
    });
}
 
Example #5
Source File: MatchStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static TraversalType getTraversalType(final Traversal.Admin<Object, Object> traversal) {
    final Step<?, ?> nextStep = traversal.getStartStep().getNextStep();
    if (nextStep instanceof WherePredicateStep)
        return TraversalType.WHERE_PREDICATE;
    else if (nextStep instanceof WhereTraversalStep)
        return TraversalType.WHERE_TRAVERSAL;
    else
        return TraversalType.MATCH_TRAVERSAL;
}
 
Example #6
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static Set<Scoping.Variable> getVariableLocations(final Set<Scoping.Variable> variables, final Traversal.Admin<?, ?> traversal) {
    if (variables.size() == 2) return variables;    // has both START and END so no need to compute further
    final Step<?, ?> startStep = traversal.getStartStep();
    if (StartStep.isVariableStartStep(startStep))
        variables.add(Scoping.Variable.START);
    else if (startStep instanceof WherePredicateStep) {
        if (((WherePredicateStep) startStep).getStartKey().isPresent())
            variables.add(Scoping.Variable.START);
    } else if (startStep instanceof WhereTraversalStep.WhereStartStep) {
        if (!((WhereTraversalStep.WhereStartStep) startStep).getScopeKeys().isEmpty())
            variables.add(Scoping.Variable.START);
    } else if (startStep instanceof MatchStep.MatchStartStep) {
        if (((MatchStep.MatchStartStep) startStep).getSelectKey().isPresent())
            variables.add(Scoping.Variable.START);
    } else if (startStep instanceof MatchStep) {
        for (final Traversal.Admin<?, ?> global : ((MatchStep<?, ?>) startStep).getGlobalChildren()) {
            TraversalHelper.getVariableLocations(variables, global);
        }
    } else if (startStep instanceof ConnectiveStep || startStep instanceof NotStep || startStep instanceof WhereTraversalStep) {
        for (final Traversal.Admin<?, ?> local : ((TraversalParent) startStep).getLocalChildren()) {
            TraversalHelper.getVariableLocations(variables, local);
        }
    }
    ///
    final Step<?, ?> endStep = traversal.getEndStep();
    if (endStep instanceof WherePredicateStep) {
        if (((WherePredicateStep) endStep).getStartKey().isPresent())
            variables.add(Scoping.Variable.END);
    } else if (endStep instanceof WhereTraversalStep.WhereEndStep) {
        if (!((WhereTraversalStep.WhereEndStep) endStep).getScopeKeys().isEmpty())
            variables.add(Scoping.Variable.END);
    } else if (endStep instanceof MatchStep.MatchEndStep) {
        if (((MatchStep.MatchEndStep) endStep).getMatchKey().isPresent())
            variables.add(Scoping.Variable.END);
    } else if (!endStep.getLabels().isEmpty())
        variables.add(Scoping.Variable.END);
    ///
    return variables;
}
 
Example #7
Source File: MatchPredicateStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    if (!TraversalHelper.hasStepOfClass(MatchStep.class, traversal))
        return;

    TraversalHelper.getStepsOfClass(MatchStep.class, traversal).forEach(matchStep -> {
        // match().select().where() --> match(where()).select()
        // match().select().dedup() --> match(dedup()).select()
        Step<?, ?> nextStep = matchStep.getNextStep();
        while (nextStep instanceof WherePredicateStep ||
                nextStep instanceof WhereTraversalStep ||
                (nextStep instanceof DedupGlobalStep && !((DedupGlobalStep) nextStep).getScopeKeys().isEmpty() && ((DedupGlobalStep) nextStep).getLocalChildren().isEmpty()) ||
                (nextStep instanceof SelectStep && ((SelectStep) nextStep).getLocalChildren().isEmpty()) ||
                (nextStep instanceof SelectOneStep && ((SelectOneStep) nextStep).getLocalChildren().isEmpty())) {
            if (nextStep instanceof WherePredicateStep || nextStep instanceof WhereTraversalStep) {
                traversal.removeStep(nextStep);
                matchStep.addGlobalChild(traversal instanceof GraphTraversal ?
                        new DefaultGraphTraversal<>().addStep(nextStep) :
                        new DefaultTraversal<>().addStep(nextStep));
                nextStep = matchStep.getNextStep();
            } else if (nextStep instanceof DedupGlobalStep && !((DedupGlobalStep) nextStep).getScopeKeys().isEmpty() && ((DedupGlobalStep) nextStep).getLocalChildren().isEmpty() && !TraversalHelper.onGraphComputer(traversal)) {
                traversal.removeStep(nextStep);
                matchStep.setDedupLabels(((DedupGlobalStep<?>) nextStep).getScopeKeys());
                nextStep = matchStep.getNextStep();
            } else if (nextStep.getLabels().isEmpty()) {
                nextStep = nextStep.getNextStep();
            } else
                break;
        }
    });
}
 
Example #8
Source File: FilterRankingStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Ranks the given step. Steps with lower ranks can be moved in front of steps with higher ranks. 0 means that
 * the step has no rank and thus is not exchangeable with its neighbors.
 *
 * @param step the step to get a ranking for
 * @return The rank of the given step.
 */
private static int getStepRank(final Step step) {
    final int rank;
    if (!(step instanceof FilterStep || step instanceof OrderGlobalStep))
        return 0;
    else if (step instanceof IsStep || step instanceof ClassFilterStep)
        rank = 1;
    else if (step instanceof HasStep)
        rank = 2;
    else if (step instanceof WherePredicateStep && ((WherePredicateStep) step).getLocalChildren().isEmpty())
        rank = 3;
    else if (step instanceof TraversalFilterStep || step instanceof NotStep)
        rank = 4;
    else if (step instanceof WhereTraversalStep)
        rank = 5;
    else if (step instanceof OrStep)
        rank = 6;
    else if (step instanceof AndStep)
        rank = 7;
    else if (step instanceof WherePredicateStep) // has by()-modulation
        rank = 8;
    else if (step instanceof DedupGlobalStep)
        rank = 9;
    else if (step instanceof OrderGlobalStep)
        rank = 10;
    else
        return 0;
    ////////////
    if (step instanceof TraversalParent)
        return getMaxStepRank((TraversalParent) step, rank);
    else
        return rank;
}
 
Example #9
Source File: SqlgWhereStrategy.java    From sqlg with MIT License 4 votes vote down vote up
@SuppressWarnings("resource")
	@Override
	public void apply(Admin<?, ?> traversal) {
		if (!(traversal.getGraph().orElseThrow(IllegalStateException::new) instanceof SqlgGraph)) {
			return;
		}
		if (!SqlgTraversalUtil.mayOptimize(traversal)) {
			return;
		}
        SqlgGraph sqlgGraph = (SqlgGraph) traversal.getGraph().get();
        //This is because in normal BatchMode the new vertices are cached with it edges.
        //The query will read from the cache if this is for a cached vertex
        if (sqlgGraph.features().supportsBatchMode() && sqlgGraph.tx().isInNormalBatchMode()) {
            sqlgGraph.tx().flush();
        }
        @SuppressWarnings("unchecked") List<Step<?,?>> steps = new ArrayList(traversal.asAdmin().getSteps());
        ListIterator<Step<?,?>> stepIterator = steps.listIterator();
        // get all steps per label
        Map<String, Object> stepsByLabel=new HashMap<>();
//        stepIterator = steps.listIterator();
        Step<?,?> previous=null;
        int idx=0;
        while (stepIterator.hasNext()) {
            Step<?,?> step = stepIterator.next();
            captureLabels(step, stepsByLabel);
            if (step instanceof WherePredicateStep<?> ){
            	WherePredicateStep<?> wps=(WherePredicateStep<?>)step;
            
	        	if (wps.getPredicate().isPresent()
	        		&& (wps.getPredicate().get().getBiPredicate() instanceof FullText
						|| wps.getPredicate().get().getBiPredicate() instanceof ArrayContains
						|| wps.getPredicate().get().getBiPredicate() instanceof ArrayOverlaps)){
	        		Object referTo=previous;
	        		if (wps.getStartKey().isPresent()){
	        			referTo=stepsByLabel.get(wps.getStartKey().get());
	        		}
	        		if (referTo instanceof SqlgGraphStep<?, ?>){
	        			SqlgGraphStep<?, ?> sgs=(SqlgGraphStep<?, ?>)referTo;
	        			if (sgs.getReplacedSteps().size()>0){
	        				referTo=sgs.getReplacedSteps().get(sgs.getReplacedSteps().size()-1);
	        			}
	        		}
	        		if (referTo instanceof ReplacedStep<?, ?>){
	        			ReplacedStep<?,?> rs=(ReplacedStep<?,?>)referTo;
	        			rs.addHasContainer(new HasContainer("__dummy__", wps.getPredicate().get()));
	        			traversal.removeStep(idx);
	        		}
	        	}
            	
            }
            previous=step;
            idx++;
        }
	}
 
Example #10
Source File: GraphTraversal.java    From tinkerpop with Apache License 2.0 2 votes vote down vote up
/**
 * Filters the current object based on the object itself or the path history.
 *
 * @param startKey  the key containing the object to filter
 * @param predicate the filter to apply
 * @return the traversal with an appended {@link WherePredicateStep}
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#where-step" target="_blank">Reference Documentation - Where Step</a>
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#using-where-with-match" target="_blank">Reference Documentation - Where with Match</a>
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#using-where-with-select" target="_blank">Reference Documentation - Where with Select</a>
 * @since 3.0.0-incubating
 */
public default GraphTraversal<S, E> where(final String startKey, final P<String> predicate) {
    this.asAdmin().getBytecode().addStep(Symbols.where, startKey, predicate);
    return this.asAdmin().addStep(new WherePredicateStep<>(this.asAdmin(), Optional.ofNullable(startKey), predicate));
}
 
Example #11
Source File: GraphTraversal.java    From tinkerpop with Apache License 2.0 2 votes vote down vote up
/**
 * Filters the current object based on the object itself or the path history.
 *
 * @param predicate the filter to apply
 * @return the traversal with an appended {@link WherePredicateStep}
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#where-step" target="_blank">Reference Documentation - Where Step</a>
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#using-where-with-match" target="_blank">Reference Documentation - Where with Match</a>
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#using-where-with-select" target="_blank">Reference Documentation - Where with Select</a>
 * @since 3.0.0-incubating
 */
public default GraphTraversal<S, E> where(final P<String> predicate) {
    this.asAdmin().getBytecode().addStep(Symbols.where, predicate);
    return this.asAdmin().addStep(new WherePredicateStep<>(this.asAdmin(), Optional.empty(), predicate));
}