org.openrdf.query.algebra.StatementPattern Java Examples
The following examples show how to use
org.openrdf.query.algebra.StatementPattern.
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: BGPGroupGenerator.java From GeoTriples with Apache License 2.0 | 6 votes |
/** * Generate BGP groups from a SPARQL query * @param parsedQuery TupleExpr of the SPARQL query * @return DNFGrps Map of DNF groups * @throws MalformedQueryException */ public static HashMap<Integer, List<StatementPattern>> generateBgpGroups(String strQuery) throws MalformedQueryException { HashMap<Integer, List<StatementPattern>> bgpGrps = new HashMap<Integer, List<StatementPattern>>(); int grpNo = 0; SPARQLParser parser = new SPARQLParser(); ParsedQuery parsedQuery = parser.parseQuery(strQuery, null); TupleExpr query = parsedQuery.getTupleExpr(); // collect all basic graph patterns for (TupleExpr bgp : BasicGraphPatternExtractor.process(query)) { //System.out.println(bgp); List<StatementPattern> patterns = StatementPatternCollector.process(bgp); bgpGrps.put(grpNo, patterns ); grpNo++; } return bgpGrps; }
Example #2
Source File: InverseObjectProperties.java From neo4j-sparql-extension with GNU General Public License v3.0 | 6 votes |
/** * Transform a statement pattern according to OWL-2 inverse properties * axiom. * * @param node the node to transform * @return list of nodes to visit next */ @Override public List<QueryModelNode> apply(StatementPattern node) { List<QueryModelNode> next = newNextList(); Var s = node.getSubjectVar(); Var p = node.getPredicateVar(); Var o = node.getObjectVar(); Var c = node.getContextVar(); URI uri = (URI) p.getValue(); String op = uri.stringValue(); Var p2; // check if need to replace with op1 or op2 if (op.equals(op1)) { p2 = new ConstVar(vf.createURI(op2)); } else { p2 = new ConstVar(vf.createURI(op1)); } StatementPattern left = node.clone(); // switch subject and object and replace predicate StatementPattern right = new StatementPattern(o, p2, s, c); node.replaceWith(new Union(left, right)); next.add(left); next.add(right); return next; }
Example #3
Source File: SubPropertyOf.java From neo4j-sparql-extension with GNU General Public License v3.0 | 6 votes |
/** * Transform a statement pattern according to OWL-2 subproperty axiom. * * @param node the node to transform * @return list of nodes to visit next */ @Override public List<QueryModelNode> apply(StatementPattern node) { List<QueryModelNode> next = newNextList(); StatementPattern left = node.clone(); // replace the predicate with the subproperty StatementPattern right = new StatementPattern( node.getSubjectVar(), new ConstVar(vf.createURI(op1)), node.getObjectVar(), node.getContextVar()); node.replaceWith( new Union(left, right)); next.add(left); next.add(right); return next; }
Example #4
Source File: SubClassOf.java From neo4j-sparql-extension with GNU General Public License v3.0 | 6 votes |
/** * Transform a statement pattern according to OWL-2 subclass axiom. * * @param node the node to transform * @return list of nodes to visit next */ @Override public List<QueryModelNode> apply(StatementPattern node) { List<QueryModelNode> next = newNextList(); StatementPattern left = node.clone(); // replace the object with the subclass StatementPattern right = new StatementPattern( node.getSubjectVar(), node.getPredicateVar(), new ConstVar(vf.createURI(ce1)), node.getContextVar()); node.replaceWith( new Union(left, right)); next.add(left); next.add(right); return next; }
Example #5
Source File: RuleTransformationVisitor.java From neo4j-sparql-extension with GNU General Public License v3.0 | 6 votes |
/** * Visits a statement pattern and tries to transform using all rules * in the given rule set. * * Tries to apply a rule from the rule set. If it is applicable * it will recurse using the visitor pattern to the nodes returned * from the rule after application. * @param node * @throws RuntimeException */ @Override public void meet(StatementPattern node) throws RuntimeException { // get a list of rules that may be applicable ArrayList<Rule> toApply = new ArrayList<>(getRules(node)); for (Rule r : toApply) { // if a rule can be applied if (r.canApply(node)) { // apply the rule List<QueryModelNode> next = r.apply(node); // visit all nodes that the rule returned for (QueryModelNode toVisit : next) { removeRule(toApply, toVisit, r); toVisit.visit(this); } // halt execution, because the rule transformed the original // node and this visit can't transform further. Remaining rules // are applied in the recursion (see above). break; } } }
Example #6
Source File: SubClassOf.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Returns true if this rule is applicable to a node. * * @param node to a node * @return true if the rule is applicable, false otherwise */ @Override public boolean canApply(StatementPattern node) { String op = getPredicate(node); String o = getObject(node); // check that the predicate is "rdf:type" and the object is the // superclass return op != null && o != null && op.equals(RDFTYPE) && o.equals(ce2); }
Example #7
Source File: StatementUnifier.java From quetzal with Eclipse Public License 2.0 | 5 votes |
/** * Computes the Most General Unifier (MGU) for two n-ary atoms. * * @param first * @param second * @return the substitution corresponding to this unification. */ public static Substitution getMGU(StatementPattern st1, StatementPattern st2) { Var term1; Var term2; Substitution mgu = new SubstitutionImpl(); for (int i = 0; i < 3; i++) { term1 = st1.getVarList().get(i); term2 = st2.getVarList().get(i); Substitution s = getUnifier(term1, term2); if (s == null) return null; if (s instanceof NeutralSubstitution) continue; SingletonSubstituion ss = (SingletonSubstituion) s; mgu.compose(ss.original, ss.substition); st1 = st1.clone(); st2 = st2.clone(); applySubstitution(mgu, st1); applySubstitution(mgu, st2); } if (mgu.isEmpty()) return new NeutralSubstitution(); return mgu; }
Example #8
Source File: Rule.java From quetzal with Eclipse Public License 2.0 | 5 votes |
public Rule getFreshRule() throws Exception { StatementPattern consequentClone = consequent.clone(); TupleExpr antecedentClone = antecedent.clone(); Set<Var> vars = new HashSet<Var>(); // vars.addAll(consequentClone.getVarList()); VarCollector vis = new VarCollector(); antecedentClone.visit(vis); consequentClone.visit(vis); vars.addAll(vis.getCollectedVars()); for (Var var : vars) { if (var.isConstant()) continue; // Var newVar = new Var(); UUID id = UUID.randomUUID(); // String uniqueStringForValue = Integer.toString(id.toString()); String uniqueStringForValue = Integer.toHexString(id.toString().hashCode()); // newVar.setName(var.getName() + "_" + uniqueStringForValue.toString()); // newVar.setAnonymous(var.isAnonymous()); VarRenamer renamer = new VarRenamer(var.getName(), var.getName() + "_" + uniqueStringForValue); antecedentClone.visit(renamer); consequentClone.visit(renamer); } Rule result = new Rule(); result.antecedent = antecedentClone; result.consequent = consequentClone; return result; }
Example #9
Source File: ObjectPropertyChain.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Transform a statement pattern according to OWL-2 property chain * axiom. * * @param node the node to transform * @return list of nodes to visit next */ @Override public List<QueryModelNode> apply(StatementPattern node) { List<QueryModelNode> next = newNextList(); Var s = node.getSubjectVar(); Var o = node.getObjectVar(); Var c = node.getContextVar(); TupleExpr left = node.clone(); TupleExpr right = getChain(s, o, c); node.replaceWith(new Union(left, right)); next.add(left); next.add(right); return next; }
Example #10
Source File: ObjectPropertyChain.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Returns true if this rule is applicable to a node. * * @param node to a node * @return true if the rule is applicable, false otherwise */ @Override public boolean canApply(StatementPattern node) { // empty chains are never applicable if (chain.isEmpty()) { return false; } // check if predicate is given object property String op1 = getPredicate(node); return op1 != null && op1.equals(op); }
Example #11
Source File: InverseObjectProperties.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Returns true if this rule is applicable to a node. * * @param node to a node * @return true if the rule is applicable, false otherwise */ @Override public boolean canApply(StatementPattern node) { String op = getPredicate(node); // check if the predicate of the statement pattern matches one // or both rule predicates return op != null && (op.equals(op1) || op.equals(op2)); }
Example #12
Source File: SubPropertyOf.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Returns true if this rule is applicable to a node. * * @param node to a node * @return true if the rule is applicable, false otherwise */ @Override public boolean canApply(StatementPattern node) { String op = getPredicate(node); // check that the predicate is the superproperty return op != null && op.equals(op2); }
Example #13
Source File: PredicateVariable.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Transform a statement pattern to infer triples for a predicate variable. * * @param node the node to transform * @return list of nodes to visit next */ @Override public List<QueryModelNode> apply(StatementPattern node) { List<QueryModelNode> next = newNextList(); StatementPattern left = node.clone(); next.add(left); TupleExpr right = assignPredicates(predicates, node.clone(), next); node.replaceWith(new Union(left, right)); return next; }
Example #14
Source File: PredicateVariable.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Returns true if this rule is applicable to a node. * * @param node to a node * @return true if the rule is applicable, false otherwise */ @Override public boolean canApply(StatementPattern node) { Var p = node.getPredicateVar(); // check if predicate is variable return !(predicates.isEmpty() || p.isConstant()); }
Example #15
Source File: RangeEvaluationStrategy.java From cumulusrdf with Apache License 2.0 | 5 votes |
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(StatementPattern sp, final BindingSet bindings) throws QueryEvaluationException { if (sp instanceof RangeStatementPattern) { return evaluate((RangeStatementPattern) sp, bindings); } else { return super.evaluate(sp, bindings); } }
Example #16
Source File: QueryOntop.java From GeoTriples with Apache License 2.0 | 5 votes |
/** * Get label for the object vertex of a triple pattern * @param stmt triple pattern * @return label Vertex label */ public static String getObjectVertexLabel(StatementPattern stmt) { String label ; if (stmt.getObjectVar().getValue()!=null) label = stmt.getObjectVar().getValue().stringValue(); else label =stmt.getObjectVar().getName(); return label; }
Example #17
Source File: QueryOntop.java From GeoTriples with Apache License 2.0 | 5 votes |
/** * Get Predicate from triple pattern * @param stmt Triple pattern * @return tuple Subject tuple */ public static String getPredicate(StatementPattern stmt) { String tuple; if (stmt.getPredicateVar().getValue()!=null) tuple = " <"+stmt.getPredicateVar().getValue().stringValue()+"> "; else tuple =" ?"+stmt.getPredicateVar().getName(); return tuple; }
Example #18
Source File: QueryOntop.java From GeoTriples with Apache License 2.0 | 5 votes |
/** * Get object from triple pattern * @param stmt Triple pattern * @return tuple Subject tuple */ public static String getObject(StatementPattern stmt) { String tuple; if (stmt.getObjectVar().getValue()!=null && (stmt.getObjectVar().getValue().toString().startsWith("http://") || stmt.getObjectVar().getValue().toString().startsWith("ftp://"))) tuple = " <"+stmt.getObjectVar().getValue().stringValue()+"> "; else if (stmt.getObjectVar().getValue()!=null) tuple = " '"+stmt.getObjectVar().getValue().stringValue()+"' "; else tuple =" ?"+stmt.getObjectVar().getName(); return tuple; }
Example #19
Source File: QueryOntop.java From GeoTriples with Apache License 2.0 | 5 votes |
public static String getTriplePattern(StatementPattern stmt) { String subject = getSubject(stmt); String object = getObject(stmt); String predicate = getPredicate(stmt); String triplePattern = subject + predicate + object ; return triplePattern; }
Example #20
Source File: QueryOntop.java From GeoTriples with Apache License 2.0 | 5 votes |
/** * Get subject from triple pattern * @param stmt Triple pattern * @return tuple Subject tuple */ public static String getSubject(StatementPattern stmt) { String tuple; if (stmt.getSubjectVar().getValue()!=null ) tuple = "<"+stmt.getSubjectVar().getValue().stringValue() + "> "; else if (stmt.getSubjectVar().getValue()!=null ) tuple = "'"+stmt.getSubjectVar().getValue().stringValue() + "' "; else tuple ="?"+stmt.getSubjectVar().getName(); return tuple; }
Example #21
Source File: QueryOntop.java From GeoTriples with Apache License 2.0 | 5 votes |
/** * Get label for the predicate vertex of a triple pattern * @param stmt triple pattern * @return label Vertex label */ public static String getPredicateVertexLabel(StatementPattern stmt) { String label ; if (stmt.getPredicateVar().getValue()!=null) label = stmt.getPredicateVar().getValue().stringValue(); else label =stmt.getPredicateVar().getName(); return label; }
Example #22
Source File: QueryOntop.java From GeoTriples with Apache License 2.0 | 5 votes |
/** * Get label for the subject vertex of a triple pattern * @param stmt triple pattern * @return label Vertex label */ public static String getSubjectVertexLabel(StatementPattern stmt) { String label ; if (stmt.getSubjectVar().getValue()!=null) label = stmt.getSubjectVar().getValue().stringValue(); else label =stmt.getSubjectVar().getName(); return label; }
Example #23
Source File: HeuristicsBasedSelectivityEstimator.java From cumulusrdf with Apache License 2.0 | 5 votes |
@Override public synchronized double getCardinality(TupleExpr expr) { if (expr instanceof RangeStatementPattern) { return rangePatternCardinality(expr); } if (expr instanceof StatementPattern) { return triplePatternCardinality(expr); } return super.getCardinality(expr); }
Example #24
Source File: CumulusQueryOptimizer.java From cumulusrdf with Apache License 2.0 | 5 votes |
@Override public void meet(final StatementPattern pattern) { pattern.getSubjectVar().setValue(makeNativeValue(pattern.getSubjectVar().getValue())); pattern.getPredicateVar().setValue(makeNativeValue(pattern.getPredicateVar().getValue())); pattern.getObjectVar().setValue(makeNativeValue(pattern.getObjectVar().getValue())); if (pattern.getContextVar() != null) { pattern.getContextVar().setValue(makeNativeValue(pattern.getContextVar().getValue())); } }
Example #25
Source File: CumulusQueryOptimizer.java From cumulusrdf with Apache License 2.0 | 5 votes |
@Override public void meet(final StatementPattern sp) { if (sp instanceof RangeStatementPattern) { if (_variables.containsKey(sp.getObjectVar())) { ((RangeStatementPattern) sp).setAscending(_variables.get(sp.getObjectVar())); } } }
Example #26
Source File: TestSubqueryPatterns.java From database with GNU General Public License v2.0 | 4 votes |
/** * Unit test for simple subquery joined with a triple pattern in the outer * join group. * * <pre> * SELECT ?s where { ?s ?x ?o . {SELECT ?x where {?x ?p ?x}}} * </pre> */ public void test_triplePattern_join_subSelect() throws MalformedQueryException, TokenMgrError, ParseException { final String sparql = "select ?s " // + "{"// + " ?s ?x ?o " + " {"// + " select ?x where { ?x ?p ?x }" // +" }"// + "}"// ; final QueryRoot expected = new QueryRoot(QueryType.SELECT); final SubqueryRoot subSelect; { { final Map<String, String> prefixDecls = new LinkedHashMap<String, String>(PrefixDeclProcessor.defaultDecls); expected.setPrefixDecls(prefixDecls); } { final ProjectionNode projection = new ProjectionNode(); projection.addProjectionVar(new VarNode("s")); expected.setProjection(projection); final JoinGroupNode whereClause = new JoinGroupNode(); expected.setWhereClause(whereClause); whereClause .addChild(new StatementPatternNode( new VarNode("s"), new VarNode("x"), new VarNode("o"), null/*c*/, StatementPattern.Scope.DEFAULT_CONTEXTS )); subSelect = new SubqueryRoot(QueryType.SELECT); // whereClause.addChild(subSelect); final JoinGroupNode wrapperGroup = new JoinGroupNode(); whereClause.addChild(wrapperGroup); wrapperGroup.addChild(subSelect); } { final ProjectionNode projection2 = new ProjectionNode(); projection2.addProjectionVar(new VarNode("x")); subSelect.setProjection(projection2); final JoinGroupNode whereClause2 = new JoinGroupNode(); subSelect.setWhereClause(whereClause2); whereClause2.addChild(new StatementPatternNode( new VarNode("x"), new VarNode("p"), new VarNode("x"), null/* c */, Scope.DEFAULT_CONTEXTS)); } } final QueryRoot actual = parse(sparql, baseURI); assertSameAST(sparql, expected, actual); }
Example #27
Source File: ConsistencyVisitor.java From neo4j-sparql-extension with GNU General Public License v3.0 | 4 votes |
@Override public void meet(StatementPattern node) throws RuntimeException { check(node); super.meet(node); }
Example #28
Source File: CumulusQueryOptimizer.java From cumulusrdf with Apache License 2.0 | 4 votes |
@Override public void meet(final StatementPattern statement) { if (statement instanceof RangeStatementPattern) { if (statement.getObjectVar().equals(_var)) { boolean equals_lower = ((RangeStatementPattern) statement).getLowerBoundEquals(); boolean equals_upper = ((RangeStatementPattern) statement).getUpperBoundEquals(); Literal lower = ((RangeStatementPattern) statement).getLowerBound(); Literal upper = ((RangeStatementPattern) statement).getUpperBound(); Literal equal = ((RangeStatementPattern) statement).getEquals(); if (_comp.equals(CompareOp.GE) || _comp.equals(CompareOp.GT)) { if (lower == null) { lower = _bound; equals_lower = _comp.equals(CompareOp.GE); } else { double currentLower = Double.parseDouble(lower.getLabel()); double newLower = Double.parseDouble(_bound.getLabel()); if (newLower > currentLower) { lower = _bound; equals_lower = _comp.equals(CompareOp.GE); } } } else if (_comp.equals(CompareOp.LE) || _comp.equals(CompareOp.LT)) { if (upper == null) { upper = _bound; equals_upper = _comp.equals(CompareOp.LE); } else { double currentUpper = Double.parseDouble(upper.getLabel()); double newUpper = Double.parseDouble(_bound.getLabel()); if (newUpper < currentUpper) { upper = _bound; equals_upper = _comp.equals(CompareOp.LE); } } } else if (_comp.equals(CompareOp.EQ)) { equal = _bound; } ((RangeStatementPattern) statement).setLowerBound(lower); ((RangeStatementPattern) statement).setUpperBound(upper); ((RangeStatementPattern) statement).setUpperBoundEquals(equals_upper); ((RangeStatementPattern) statement).setLowerBoundEquals(equals_lower); ((RangeStatementPattern) statement).setEquals(equal); } } else { if (statement.getObjectVar().equals(_var)) { boolean equals_lower = false, equals_upper = false; boolean replace = false; Literal upper = null, lower = null, equals = null; if (_comp.equals(CompareOp.GE) || _comp.equals(CompareOp.GT)) { lower = _bound; equals_lower = _comp.equals(CompareOp.GE); replace = true; } else if (_comp.equals(CompareOp.EQ)) { equals = _bound; replace = true; } else if (_comp.equals(CompareOp.LE) || _comp.equals(CompareOp.LT)) { upper = _bound; equals_upper = _comp.equals(CompareOp.LE); replace = true; } if (replace) { RangeStatementPattern newP = new RangeStatementPattern(statement.getSubjectVar(), statement.getPredicateVar(), statement.getObjectVar(), lower, equals_lower, upper, equals_upper, equals); statement.replaceWith(newP); } } } }
Example #29
Source File: Rule.java From quetzal with Eclipse Public License 2.0 | 4 votes |
private void extractConsequent(TupleExpr constructQuery, Projection projection, Extension extension) { StatementPattern consequent = new StatementPattern(); Var sub = new Var(); Var pred = new Var(); Var obj = new Var(); HashMap<String, ValueConstant> index = new HashMap<String, ValueConstant>(); for (ExtensionElem extElem: extension.getElements()) { try { index.put(extElem.getName(), (ValueConstant) extElem.getExpr()); } catch (ClassCastException e) { e.printStackTrace(); throw new RuntimeException("Unsupported construct query rule: \n" + constructQuery.toString()); } } for (ProjectionElem elem: projection.getProjectionElemList().getElements()) { Var currentComponent = null; if (elem.getTargetName().equals("subject")) { currentComponent = sub; } else if (elem.getTargetName().equals("predicate")) { currentComponent = pred; } else if (elem.getTargetName().equals("object")) { currentComponent = obj; } else { throw new RuntimeException("Unsupported construct query rule: " + constructQuery.toString()); } ValueConstant valueConstant = index.get(elem.getSourceName()); if (valueConstant != null) { currentComponent.setConstant(true); currentComponent.setValue(valueConstant.getValue()); currentComponent.setName(elem.getSourceName()); } else { currentComponent.setConstant(false); currentComponent.setName(elem.getSourceName()); } } consequent.setSubjectVar(sub); consequent.setPredicateVar(pred); consequent.setObjectVar(obj); this.consequent = consequent; }
Example #30
Source File: ResolutionEngine.java From quetzal with Eclipse Public License 2.0 | 4 votes |
/**** * If the visited pattern unifies with rule, and the node has not been * visited, it will replace the node (in the nodes parent) with a union * consisting of the node unified with the body of all the rules that * unified with the node. */ @Override public void meet(StatementPattern node) { if (visited.contains(node)) return; visited.add(node); QueryModelNode parent = node.getParentNode(); List<TupleExpr> nodeAlternatives = new LinkedList<TupleExpr>(); nodeAlternatives.add(node); for (Rule rule : rules) { try { rule = rule.getFreshRule(); } catch (Exception e) { throw new RuntimeException(e); } Substitution s = StatementUnifier.getMGU(node, rule.consequent); if (s == null) continue; // The rule matches the node, replacing (executing a resolution // step) // Preparing the body of the rule TupleExpr body = rule.antecedent; SubstitutionApplier app = new SubstitutionApplier(s); body.visit(app); /* If the substitution affects any variables in the domain of the original query then we need to add a BIND(...) element, using extensions, for example. If x is in the original query, and we have the substition x/<example.org> we need the extension BIND(<example.org> as ?x) */ Extension ex = new Extension(); for (Var var: s.getMap().keySet()) { String name = var.getName(); if (!queryBindingNames.contains(name)) { continue; } Var expr = s.get(var); ex.addElement(new ExtensionElem(expr, name)); } TupleExpr newExpression; if (!ex.getElements().isEmpty()) { ex.setArg(body); newExpression = ex; } else { newExpression = body; } nodeAlternatives.add(newExpression); } if (nodeAlternatives.size() == 1) { // There was no resolution, no change return; } // constructing UNION operator, a binary tree, removing 2 at a time Union union = null; while (!nodeAlternatives.isEmpty()) { Union newunion = null; if (union == null) { newunion = new Union(nodeAlternatives.remove(0), nodeAlternatives.remove(0)); } else { newunion = new Union(nodeAlternatives.remove(0), union); } union = newunion; } // replacing the node with the constructed union parent.replaceChildNode(node, union); producedChange = true; }