org.apache.tinkerpop.gremlin.process.traversal.Compare Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.Compare. 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: NativeTitan1GraphQuery.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
private Compare getGremlinPredicate(ComparisionOperator op) {
    switch (op) {
        case EQUAL:
            return Compare.eq;
        case GREATER_THAN:
            return Compare.gt;
        case GREATER_THAN_EQUAL:
            return Compare.gte;
        case LESS_THAN:
            return Compare.lt;
        case LESS_THAN_EQUAL:
            return Compare.lte;
        case NOT_EQUAL:
            return Compare.neq;

        default:
            throw new RuntimeException("Unsupported comparison operator:" + op);
    }
}
 
Example #2
Source File: WhereClause.java    From sqlg with MIT License 6 votes vote down vote up
private static String compareToSql(Compare compare, String column) {
    switch (compare) {
        case eq:
            return " = " + column;
        case neq:
            return " <> " + column;
        case gt:
            return " > " + column;
        case gte:
            return " >= " + column;
        case lt:
            return " < " + column;
        case lte:
            return " <= " + column;
        default:
            throw new RuntimeException("Unknown Compare " + compare.name());
    }
}
 
Example #3
Source File: WhereClause.java    From sqlg with MIT License 6 votes vote down vote up
private static String compareToSql(Compare compare) {
    switch (compare) {
        case eq:
            return " = ?";
        case neq:
            return " <> ?";
        case gt:
            return " > ?";
        case gte:
            return " >= ?";
        case lt:
            return " < ?";
        case lte:
            return " <= ?";
        default:
            throw new RuntimeException("Unknown Compare " + compare.name());
    }
}
 
Example #4
Source File: TestPropertyReference.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testMultiplePath(){
 Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "johnny", "score",2,"experience",3);
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "pietie", "score",2,"experience",2);
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person", "name", "koosie", "score",2,"experience",1);
      
    Vertex v4 = this.sqlgGraph.addVertex(T.label, "Group", "name", "Friends");
    v4.addEdge("contains", v1);
    v4.addEdge("contains", v2);
    v4.addEdge("contains", v3);
    
    Vertex v5 = this.sqlgGraph.addVertex(T.label, "Company", "name", "Acme");
    v5.addEdge("groups", v4);
    
    this.sqlgGraph.tx().commit();
   
    GraphTraversal<Vertex, Map<String,Object>> traversal =sqlgGraph.traversal()
   		 .V().hasLabel("Company").as("c").out("groups")
   		 .as("g").out("contains").has("score",propertyRef(Compare.eq, "experience")).as("p")
   		 .select("c","p");
    List<Map<String,Object>> l =traversal.toList();
    assertEquals(1,l.size());
    assertEquals(v2,l.get(0).get("p"));
}
 
Example #5
Source File: TraversalUtil.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
public static Condition convHas2Condition(HasContainer has,
                                          HugeType type,
                                          HugeGraph graph) {
    P<?> p = has.getPredicate();
    E.checkArgument(p != null, "The predicate of has(%s) is null", has);
    BiPredicate<?, ?> bp = p.getBiPredicate();
    Condition condition;
    if (keyForContainsKeyOrValue(has.getKey())) {
        condition = convContains2Relation(graph, has);
    } else if (bp instanceof Compare) {
        condition = convCompare2Relation(graph, type, has);
    } else if (bp instanceof RelationType) {
        condition = convRelationType2Relation(graph, type, has);
    } else if (bp instanceof Contains) {
        condition = convIn2Relation(graph, type, has);
    } else if (p instanceof AndP) {
        condition = convAnd(graph, type, has);
    } else if (p instanceof OrP) {
        condition = convOr(graph, type, has);
    } else {
        // TODO: deal with other Predicate
        throw newUnsupportedPredicate(p);
    }
    return condition;
}
 
Example #6
Source File: TitanPredicate.java    From titan1withtp3.1 with Apache License 2.0 6 votes vote down vote up
/**
 * Convert Tinkerpop's comparison operators to Titan's
 *
 * @param p Any predicate
 * @return A TitanPredicate equivalent to the given predicate
 * @throws IllegalArgumentException if the given Predicate is unknown
 */
public static final TitanPredicate convertInternal(BiPredicate p) {
    if (p instanceof TitanPredicate) {
        return (TitanPredicate)p;
    } else if (p instanceof Compare) {
        Compare comp = (Compare)p;
        switch(comp) {
            case eq: return Cmp.EQUAL;
            case neq: return Cmp.NOT_EQUAL;
            case gt: return Cmp.GREATER_THAN;
            case gte: return Cmp.GREATER_THAN_EQUAL;
            case lt: return Cmp.LESS_THAN;
            case lte: return Cmp.LESS_THAN_EQUAL;
            default: throw new IllegalArgumentException("Unexpected comparator: " + comp);
        }
    } else if (p instanceof Contains) {
        Contains con = (Contains)p;
        switch (con) {
            case within: return Contain.IN;
            case without: return Contain.NOT_IN;
            default: throw new IllegalArgumentException("Unexpected container: " + con);

        }
    } else return null;
}
 
Example #7
Source File: HBaseVertexStep.java    From hgraphdb with Apache License 2.0 6 votes vote down vote up
private Iterator<Edge> lookupEdges(final Traverser.Admin<Vertex> traverser, final List<HasContainer> hasContainers) {
    final HBaseGraph graph = (HBaseGraph) this.getTraversal().getGraph().get();
    if (getEdgeLabels().length == 1) {
        final String label = getEdgeLabels()[0];
        // find an edge by label and key/value
        for (final HasContainer hasContainer : hasContainers) {
            if (Compare.eq == hasContainer.getBiPredicate() && !hasContainer.getKey().equals(T.label.getAccessor())) {
                if (graph.hasIndex(OperationType.READ, ElementType.EDGE, label, hasContainer.getKey())) {
                    return IteratorUtils.stream(((HBaseVertex) traverser.get()).edges(getDirection(), label, hasContainer.getKey(), hasContainer.getValue()))
                            .filter(vertex -> HasContainer.testAll(vertex, hasContainers)).iterator();
                }
            }
        }
    }

    // linear scan
    return CloseableIteratorUtils.filter(traverser.get().edges(getDirection(), getEdgeLabels()),
            edge -> HasContainer.testAll(edge, hasContainers));
}
 
Example #8
Source File: NativeJanusGraphQuery.java    From atlas with Apache License 2.0 6 votes vote down vote up
private Compare getGremlinPredicate(ComparisionOperator op) {
    switch (op) {
        case EQUAL:
            return Compare.eq;
        case GREATER_THAN:
            return Compare.gt;
        case GREATER_THAN_EQUAL:
            return Compare.gte;
        case LESS_THAN:
            return Compare.lt;
        case LESS_THAN_EQUAL:
            return Compare.lte;
        case NOT_EQUAL:
            return Compare.neq;

        default:
            throw new RuntimeException("Unsupported comparison operator:" + op);
    }
}
 
Example #9
Source File: JanusGraphPredicate.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Convert Tinkerpop's comparison operators to JanusGraph's
 *
 * @param p Any predicate
 * @return A JanusGraphPredicate equivalent to the given predicate
 * @throws IllegalArgumentException if the given Predicate is unknown
 */
public static JanusGraphPredicate convertInternal(BiPredicate p) {
    if (p instanceof JanusGraphPredicate) {
        return (JanusGraphPredicate) p;
    } else if (p instanceof Compare) {
        final Compare comp = (Compare) p;
        switch (comp) {
            case eq:
                return Cmp.EQUAL;
            case neq:
                return Cmp.NOT_EQUAL;
            case gt:
                return Cmp.GREATER_THAN;
            case gte:
                return Cmp.GREATER_THAN_EQUAL;
            case lt:
                return Cmp.LESS_THAN;
            case lte:
                return Cmp.LESS_THAN_EQUAL;
            default:
                throw new IllegalArgumentException("Unexpected comparator: " + comp);
        }
    } else if (p instanceof Contains) {
        final Contains con = (Contains) p;
        switch (con) {
            case within:
                return Contain.IN;
            case without:
                return Contain.NOT_IN;
            default:
                throw new IllegalArgumentException("Unexpected container: " + con);

        }
    } else return null;
}
 
Example #10
Source File: NativeTitan1GraphQuery.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Override
public void has(String propertyName, QueryOperator op, Object value) {
    TitanPredicate pred;
    if (op instanceof ComparisionOperator) {
        Compare c = getGremlinPredicate((ComparisionOperator) op);
        pred = TitanPredicate.Converter.convert(c);
    } else {
        pred = getGremlinPredicate((MatchingOperator)op);
    }
    query.has(propertyName, pred, value);
}
 
Example #11
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 #12
Source File: GraphStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for providers that want to "fold in" {@link HasContainer}'s based on id checking into the ids of the {@link GraphStep}.
 *
 * @param graphStep    the GraphStep to potentially {@link GraphStep#addIds(Object...)}.
 * @param hasContainer The {@link HasContainer} to check for id validation.
 * @return true if the {@link HasContainer} updated ids and thus, was processed.
 */
public static boolean processHasContainerIds(final GraphStep<?, ?> graphStep, final HasContainer hasContainer) {
    if (hasContainer.getKey().equals(T.id.getAccessor()) && graphStep.ids.length == 0 &&
            (hasContainer.getBiPredicate() == Compare.eq || hasContainer.getBiPredicate() == Contains.within)) {
        graphStep.addIds(hasContainer.getValue());
        return true;
    }
    return false;
}
 
Example #13
Source File: TinkerGraphStep.java    From tinkerpop with Apache License 2.0 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 #14
Source File: TestPropertyReference.java    From sqlg with MIT License 5 votes vote down vote up
@Test
public void testInt() {
 Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "johnny", "score",2,"experience",3);
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "pietie", "score",2,"experience",2);
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person", "name", "koosie", "score",2,"experience",1);
      
    this.sqlgGraph.tx().commit();
    
    assertOneStepOneVertex(this.sqlgGraph.traversal().V().hasLabel("Person").has("score",propertyRef(Compare.eq, "experience"))
   		 ,v2);
    assertOneStepOneVertex(this.sqlgGraph.traversal().V().hasLabel("Person").has("score",propertyRef(Compare.lt, "experience"))
   		 ,v1);
    assertOneStepOneVertex(this.sqlgGraph.traversal().V().hasLabel("Person").has("score",propertyRef(Compare.gt, "experience"))
   		 ,v3);
}
 
Example #15
Source File: TinkerGraphStep.java    From tinkergraph-gremlin with Apache License 2.0 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 #16
Source File: NativeJanusGraphQuery.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
public void has(String propertyName, QueryOperator op, Object value) {
    JanusGraphPredicate pred;
    if (op instanceof ComparisionOperator) {
        Compare c = getGremlinPredicate((ComparisionOperator) op);
        pred = JanusGraphPredicateUtils.convert(c);
    } else {
        pred = getGremlinPredicate((MatchingOperator)op);
    }
    query.has(propertyName, pred, value);
}
 
Example #17
Source File: AdjacentVertexFilterOptimizerStrategy.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void apply(Traversal.Admin<?, ?> traversal) {

    TraversalHelper.getStepsOfClass(TraversalFilterStep.class, traversal).forEach(originalStep -> {
        // Check if this filter traversal matches the pattern: _.inV/outV/otherV.is(x)
        Traversal.Admin<?, ?> filterTraversal = (Traversal.Admin<?, ?>) originalStep.getLocalChildren().get(0);
        List<Step> steps = filterTraversal.getSteps();
        if (steps.size() == 2 &&
                (steps.get(0) instanceof EdgeVertexStep || steps.get(0) instanceof EdgeOtherVertexStep) &&
                (steps.get(1) instanceof IsStep)) {
            //Get the direction in which we filter on the adjacent vertex (or null if not a valid adjacency filter)
            Direction direction = null;
            if (steps.get(0) instanceof EdgeVertexStep) {
                EdgeVertexStep evs = (EdgeVertexStep) steps.get(0);
                if (evs.getDirection() != Direction.BOTH) direction = evs.getDirection();
            } else {
                direction = Direction.BOTH;
            }
            P predicate = ((IsStep) steps.get(1)).getPredicate();
            //Check that we have a valid direction and a valid vertex filter predicate
            if (direction != null && predicate.getBiPredicate() == Compare.eq && predicate.getValue() instanceof Vertex) {
                Vertex vertex = (Vertex) predicate.getValue();

                //Now, check that this step is preceded by VertexStep that returns edges
                Step<?, ?> currentStep = originalStep.getPreviousStep();
                while (currentStep != EmptyStep.instance()) {
                    if (!(currentStep instanceof HasStep) && !(currentStep instanceof IdentityStep)) {
                        break;
                    } //We can jump over other steps as we move backward
                    currentStep = currentStep.getPreviousStep();
                }
                if (currentStep instanceof VertexStep) {
                    VertexStep vertexStep = (VertexStep) currentStep;
                    if (vertexStep.returnsEdge()
                            && (direction == Direction.BOTH || direction.equals(vertexStep.getDirection().opposite()))) {
                        //Now replace the step with a has condition
                        TraversalHelper.replaceStep(originalStep,
                            new HasStep(traversal, new HasContainer(ImplicitKey.ADJACENT_ID.name(), P.eq(vertex))),
                            traversal);
                    }
                }

            }
        }

    });

}
 
Example #18
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldHandlePredicate() {
    P p = new P(Compare.eq, 10);
    assertParameterizedTranslation(String.format("new java.util.Date(%s)", p.toString()), 10);
}
 
Example #19
Source File: PropertyReference.java    From sqlg with MIT License 4 votes vote down vote up
private RefP(Compare biPredicate, PropertyReference value) {
	super(biPredicate, value);
}
 
Example #20
Source File: PropertyReference.java    From sqlg with MIT License 2 votes vote down vote up
/**
 * build a predicate from a compare operation and a column name
 * @param p
 * @param columnName
 * @return
 */
public static P<Object> propertyRef(Compare p,String columnName){
	return new RefP(p, new PropertyReference(columnName));
}