org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor. 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: QueryJoinOptimizerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES2306AggregateOrderBy() throws Exception {
	String select = "PREFIX ex: <ex:>\n" + "SELECT ((MIN(?x+1) + MAX(?y-1))/2 AS ?r) {\n"
			+ "	?this ex:name ?n . ?this ex:id ?id . ?this ex:prop1 ?x . ?this ex:prop2 ?y .\n"
			+ "} GROUP BY concat(?n, ?id) HAVING (SUM(?x) + SUM(?y) < 5) ORDER BY (COUNT(?x) + COUNT(?y))";

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery q = parser.parseQuery(select, null);
	q.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {

		@Override
		protected void meetUnaryTupleOperator(UnaryTupleOperator node) throws Exception {
			assertNotEquals(node, node.getArg());
			super.meetUnaryTupleOperator(node);
		}
	});
}
 
Example #2
Source File: SPARQLQueryExecutor.java    From semagrow with Apache License 2.0 6 votes vote down vote up
/**
 * Compute the variable names occurring in the service expression using tree
 * traversal, since these are necessary for building the SPARQL query.
 *
 * @return the set of variable names in the given service expression
 */
protected Set<String> computeVars(TupleExpr serviceExpression) {
    final Set<String> res = new HashSet<String>();
    serviceExpression.visit(new AbstractQueryModelVisitor<RuntimeException>() {

        @Override
        public void meet(Var node)
                throws RuntimeException {
            // take only real vars, i.e. ignore blank nodes
            if (!node.hasValue() && !node.isAnonymous())
                res.add(node.getName());
        }
        // TODO maybe stop tree traversal in nested SERVICE?
        // TODO special case handling for BIND
    });
    return res;
}
 
Example #3
Source File: SPARQLQueryExecutor.java    From semagrow with Apache License 2.0 6 votes vote down vote up
/**
 * Compute the variable names occurring in the service expression using tree
 * traversal, since these are necessary for building the SPARQL query.
 *
 * @return the set of variable names in the given service expression
 */
protected Set<String> computeVars(TupleExpr serviceExpression) {
    final Set<String> res = new HashSet<String>();
    serviceExpression.visit(new AbstractQueryModelVisitor<RuntimeException>() {

        @Override
        public void meet(Var node)
                throws RuntimeException {
            // take only real vars, i.e. ignore blank nodes
            if (!node.hasValue() && !node.isAnonymous())
                res.add(node.getName());
        }
        // TODO maybe stop tree traversal in nested SERVICE?
        // TODO special case handling for BIND
    });
    return res;
}
 
Example #4
Source File: SPARQLQueryStringUtil.java    From semagrow with Apache License 2.0 6 votes vote down vote up
/**
 * Compute the variable names occurring in the service expression using tree
 * traversal, since these are necessary for building the SPARQL query.
 *
 * @return the set of variable names in the given service expression
 */
private static Set<String> computeVars(TupleExpr serviceExpression) {
    final Set<String> res = new HashSet<String>();
    serviceExpression.visit(new AbstractQueryModelVisitor<RuntimeException>() {

        @Override
        public void meet(Var node)
                throws RuntimeException
        {
            // take only real vars, i.e. ignore blank nodes
            if (!node.hasValue() && !node.isAnonymous())
                res.add(node.getName());
        }
        // TODO maybe stop tree traversal in nested SERVICE?
        // TODO special case handling for BIND
    });
    return res;
}
 
Example #5
Source File: ParsedQueryUtil.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the first {@link Projection} node within a {@link ParsedQuery}.
 *
 * @param query - The query that will be searched. (not null)
 * @return The first projection encountered if the query has one; otherwise absent.
 */
public Optional<Projection> findProjection(final ParsedQuery query) {
    checkNotNull(query);

    // When a projection is encountered for the requested index, store it in atomic reference and quit searching.
    final AtomicReference<Projection> projectionRef = new AtomicReference<>();

    query.getTupleExpr().visit(new AbstractQueryModelVisitor<RuntimeException>() {
        @Override
        public void meet(Projection projection) {
            projectionRef.set(projection);
        }
    });

    return Optional.fromNullable( projectionRef.get() );
}
 
Example #6
Source File: StatementPatternMatcherTest.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch the {@link StatementPattern} from a SPARQL string.
 *
 * @param sparql - A SPARQL query that contains only a single Statement Patern. (not nul)
 * @return The {@link StatementPattern} that was in the query, if it could be found. Otherwise {@code null}
 * @throws Exception The statement pattern could not be found in the parsed SPARQL query.
 */
public static @Nullable StatementPattern getSp(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<StatementPattern> statementPattern = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visitChildren(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final StatementPattern node) throws Exception {
            statementPattern.set(node);
        }
    });
    return statementPattern.get();
}
 
Example #7
Source File: ThetaJoinPredicate.java    From semagrow with Apache License 2.0 5 votes vote down vote up
public void replaceWith(Quantifier.Var v1, ValueExpr e) {
    theta.visit(new AbstractQueryModelVisitor<RuntimeException>() {
        @Override
        public void meetNode(QueryModelNode node) throws RuntimeException {
            if (node instanceof Quantifier.Var) {
                Quantifier.Var v = (Quantifier.Var)node;
                if (v.equals(v1))
                    node.replaceWith(e);
            }
            super.meetNode(node);
        }
    });
}
 
Example #8
Source File: TupleExprs.java    From semagrow with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the set of the unbounded variables of a {@link TupleExpr}
 * @param expr a tuple expression
 * @return a set of variable names
 */
public static Set<String> getFreeVariables(TupleExpr expr){
    final Set<String> res = new HashSet<String>();
    expr.visit(new AbstractQueryModelVisitor<RuntimeException>() {

        @Override
        public void meet(Var node)
                throws RuntimeException {
            // take only real vars, i.e. ignore blank nodes
            if (!node.hasValue() && !node.isAnonymous())
                res.add(node.getName());
        }
    });
    return res;
}
 
Example #9
Source File: RdfTestUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link Filter} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link Filter} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable Filter getFilter(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<Filter> filter = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final Filter node) throws Exception {
            filter.set(node);
        }
    });

    return filter.get();
}
 
Example #10
Source File: RdfTestUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link MultiProjection} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link MultiProjection} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable MultiProjection getMultiProjection(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<MultiProjection> multiProjection = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final MultiProjection node) throws Exception {
            multiProjection.set(node);
        }
    });

    return multiProjection.get();
}
 
Example #11
Source File: RdfTestUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link Projection} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link Projection} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable Projection getProjection(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<Projection> projection = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final Projection node) throws Exception {
            projection.set(node);
        }
    });

    return projection.get();
}
 
Example #12
Source File: RdfTestUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch the {@link StatementPattern} from a SPARQL string.
 *
 * @param sparql - A SPARQL query that contains only a single Statement Pattern. (not null)
 * @return The {@link StatementPattern} that was in the query, if it could be found. Otherwise {@code null}
 * @throws Exception The statement pattern could not be found in the parsed SPARQL query.
 */
public static @Nullable StatementPattern getSp(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<StatementPattern> statementPattern = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visitChildren(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final StatementPattern node) throws Exception {
            statementPattern.set(node);
        }
    });
    return statementPattern.get();
}
 
Example #13
Source File: FilterEvaluatorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link Filter} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link Filter} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable Filter getFilter(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<Filter> filter = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final Filter node) throws Exception {
            filter.set(node);
        }
    });

    return filter.get();
}
 
Example #14
Source File: CustomGraphQueryInferencer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Called in order to set all the fields needed for the inferencer to function.
 *
 * @param language    language that <tt>queryText</tt> and <tt>matcherText</tt> are expressed in
 * @param queryText   a query that returns an RDF graph of inferred statements to be added to the underlying Sail
 * @param matcherText a query that returns an RDF graph of existing inferred statements already added previously
 * @throws MalformedQueryException if there is a problem parsing either of the given queries
 * @throws SailException           if a problem occurs interpreting the rule pattern
 */
public final void setFields(QueryLanguage language, String queryText, String matcherText)
		throws MalformedQueryException, SailException {
	customQuery = QueryParserUtil.parseGraphQuery(language, queryText, null);
	String matcherQuery = matcherText;
	if (matcherText.trim().isEmpty()) {
		matcherQuery = CustomGraphQueryInferencerConfig.buildMatcherQueryFromRuleQuery(language, queryText);
	}
	customMatcher = QueryParserUtil.parseGraphQuery(language, matcherQuery, null);
	customQuery.getTupleExpr().visit(new AbstractQueryModelVisitor<SailException>() {

		@Override
		public void meet(StatementPattern statement) throws SailException {
			Var var = statement.getSubjectVar();
			if (var.hasValue()) {
				watchSubjects.add(var.getValue());
			}
			var = statement.getPredicateVar();
			if (var.hasValue()) {
				watchPredicates.add(var.getValue());
			}
			var = statement.getObjectVar();
			if (var.hasValue()) {
				watchObjects.add(var.getValue());
			}
		}
	});
	hasWatchValues = !(watchSubjects.isEmpty() && watchPredicates.isEmpty() && watchObjects.isEmpty());
}
 
Example #15
Source File: ProjectionEvaluatorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link Projection} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link Projection} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable Projection getProjection(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<Projection> projection = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final Projection node) throws Exception {
            projection.set(node);
        }
    });

    return projection.get();
}
 
Example #16
Source File: MultiProjectionEvaluatorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link MultiProjection} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link MultiProjection} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable MultiProjection getMultiProjection(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<MultiProjection> multiProjection = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final MultiProjection node) throws Exception {
            multiProjection.set(node);
        }
    });

    return multiProjection.get();
}
 
Example #17
Source File: AggregationsEvaluator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Make an instance of {@link AggregationsEvaluator} based on a {@link Group} node.
 *
 * @param aggStateStore - The mechanism for storing aggregation state. (not null)
 * @param aggNode - Defines which aggregation functions need to be performed.
 * @param groupByVars - The names of the binding whose values are used to group aggregation results. (not null)
 * @return The evaluator that handles the node's aggregations.
 */
public static  AggregationsEvaluator make(final AggregationStateStore aggStateStore, final Group aggNode, final List<String> groupByVars) {
    requireNonNull(aggStateStore);
    requireNonNull(aggNode);
    requireNonNull(groupByVars);

    // The aggregations that need to be performed are the Group Elements.
    final List<AggregationElement> aggregations = new ArrayList<>();
    for(final GroupElem groupElem : aggNode.getGroupElements()) {
        // Figure out the type of the aggregation.
        final AggregateOperator operator = groupElem.getOperator();
        final Optional<AggregationType> type = AggregationType.byOperatorClass( operator.getClass() );

        // If the type is one we support, create the AggregationElement.
        if(type.isPresent()) {
            final String resultBindingName = groupElem.getName();

            final AtomicReference<String> aggregatedBindingName = new AtomicReference<>();
            groupElem.visitChildren(new AbstractQueryModelVisitor<RuntimeException>() {
                @Override
                public void meet(final Var node) {
                    aggregatedBindingName.set( node.getName() );
                }
            });

            aggregations.add( new AggregationElement(type.get(), aggregatedBindingName.get(), resultBindingName) );
        }
    }

    return new AggregationsEvaluator(aggStateStore, aggregations, groupByVars);
}
 
Example #18
Source File: HalyardQueryJoinOptimizerTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryJoinOptimizarWithBind() {
    final TupleExpr expr = new SPARQLParser().parseQuery("SELECT * WHERE { BIND (<http://whatever/> AS ?b)  ?a <http://whatever/> ?b , \"whatever\".}", "http://baseuri/").getTupleExpr();
    new HalyardQueryJoinOptimizer(new HalyardEvaluationStatistics(null, null)).optimize(expr, null, null);
    expr.visit(new AbstractQueryModelVisitor<RuntimeException>(){
        @Override
        public void meet(Join node) throws RuntimeException {
            if (node.getLeftArg() instanceof StatementPattern) {
                assertEquals(expr.toString(), "b", ((StatementPattern)node.getLeftArg()).getObjectVar().getName());
            }
        }
    });
}
 
Example #19
Source File: HalyardQueryJoinOptimizerTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryJoinOptimizerWithSplitFunction() {
    final TupleExpr expr = new SPARQLParser().parseQuery("select * where {?a a \"1\";?b ?d. filter (<" + HALYARD.PARALLEL_SPLIT_FUNCTION + ">(10, ?d))}", "http://baseuri/").getTupleExpr();
    new HalyardQueryJoinOptimizer(new HalyardEvaluationStatistics(null, null)).optimize(expr, null, null);
    expr.visit(new AbstractQueryModelVisitor<RuntimeException>(){
        @Override
        public void meet(Join node) throws RuntimeException {
            assertEquals(expr.toString(), "d", ((StatementPattern)node.getLeftArg()).getObjectVar().getName());
            assertTrue(expr.toString(), ((StatementPattern)node.getRightArg()).getObjectVar().hasValue());
        }
    });
}
 
Example #20
Source File: HalyardQueryJoinOptimizerTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryJoinOptimizer() {
    final TupleExpr expr = new SPARQLParser().parseQuery("select * where {?a ?b ?c, \"1\".}", "http://baseuri/").getTupleExpr();
    new HalyardQueryJoinOptimizer(new HalyardEvaluationStatistics(null, null)).optimize(expr, null, null);
    expr.visit(new AbstractQueryModelVisitor<RuntimeException>(){
        @Override
        public void meet(Join node) throws RuntimeException {
            assertTrue(expr.toString(), ((StatementPattern)node.getLeftArg()).getObjectVar().hasValue());
            assertEquals(expr.toString(), "c", ((StatementPattern)node.getRightArg()).getObjectVar().getName());
        }
    });
}
 
Example #21
Source File: Service.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Compute the variable names occurring in the service expression using tree traversal, since these are necessary
 * for building the SPARQL query.
 *
 * @return the set of variable names in the given service expression
 */
private Set<String> computeServiceVars(TupleExpr serviceExpression) {
	final Set<String> res = new HashSet<>();
	serviceExpression.visit(new AbstractQueryModelVisitor<RuntimeException>() {

		@Override
		public void meet(Var node) throws RuntimeException {
			// take only real vars, i.e. ignore blank nodes
			if (!node.hasValue() && !node.isAnonymous()) {
				res.add(node.getName());
			}
		}

		@Override
		public void meet(BindingSetAssignment bsa) {
			res.addAll(bsa.getAssuredBindingNames());
		}

		@Override
		public void meet(Extension e) {
			super.meet(e);
			for (ExtensionElem elem : e.getElements()) {
				res.add(elem.getName());
			}
		}
		// TODO maybe stop tree traversal in nested SERVICE?
	});
	return res;
}
 
Example #22
Source File: AbstractBulkJoinPlanNode.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void updateQuery(ParsedQuery parsedQuery, List<BindingSet> newBindindingset) {
	try {
		parsedQuery.getTupleExpr()
				.visitChildren(new AbstractQueryModelVisitor<Exception>() {
					@Override
					public void meet(BindingSetAssignment node) {
						node.setBindingSets(newBindindingset);
					}
				});
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #23
Source File: StatementPatternStorage.java    From rya with Apache License 2.0 4 votes vote down vote up
protected void addStatementPatternRange(String subj, String pred, String obj, String ctxt) throws IOException {
    logger.info("Adding statement pattern[subject:" + subj + ", predicate:" + pred + ", object:" + obj + ", context:" + ctxt + "]");
    StringBuilder sparqlBuilder = new StringBuilder();
    sparqlBuilder.append("select * where {\n");
    if (ctxt != null) {
        /**
         * select * where {
         GRAPH ?g {
         <http://www.example.org/exampleDocument#Monica> ?p ?o.
         }
         }
         */
        sparqlBuilder.append("GRAPH ").append(ctxt).append(" {\n");
    }
    sparqlBuilder.append(subj).append(" ").append(pred).append(" ").append(obj).append(".\n");
    if (ctxt != null) {
        sparqlBuilder.append("}\n");
    }
    sparqlBuilder.append("}\n");
    String sparql = sparqlBuilder.toString();

    if (logger.isDebugEnabled()) {
        logger.debug("Sparql statement range[" + sparql + "]");
    }

    QueryParser parser = new SPARQLParser();
    ParsedQuery parsedQuery = null;
    try {
        parsedQuery = parser.parseQuery(sparql, null);
    } catch (MalformedQueryException e) {
        throw new IOException(e);
    }
    parsedQuery.getTupleExpr().visitChildren(new AbstractQueryModelVisitor<IOException>() {
        @Override
        public void meet(StatementPattern node) throws IOException {
            Var subjectVar = node.getSubjectVar();
            Var predicateVar = node.getPredicateVar();
            Var objectVar = node.getObjectVar();
            subject_value = getValue(subjectVar);
            predicate_value = getValue(predicateVar);
            object_value = getValue(objectVar);
            Var contextVar = node.getContextVar();
            Map.Entry<TABLE_LAYOUT, Range> temp = createRange(subject_value, predicate_value, object_value);
            layout = temp.getKey();
            Range range = temp.getValue();
            addRange(range);
            if (contextVar != null && contextVar.getValue() != null) {
                String context_str = contextVar.getValue().stringValue();
                addColumnPair(context_str, "");
            }
        }
    });
}