Search in sources :

Example 1 with ListBindingSet

use of org.openrdf.query.impl.ListBindingSet in project QueryAnalysis by Wikidata.

the class OpenRDFQueryHandler method normalize.

/**
 * Normalizes a given query by:
 * - replacing all wikidata uris at subject and object positions with sub1, sub2 ... (obj1, obj2 ...).
 *
 * @param queryToNormalize the query to be normalized
 * @return the normalized query
 * @throws MalformedQueryException If the query was malformed (would be a bug since the input was a parsed query)
 * @throws VisitorException        If there is an error during normalization
 */
private ParsedQuery normalize(ParsedQuery queryToNormalize) throws MalformedQueryException, VisitorException {
    ParsedQuery normalizedQuery = new StandardizingSPARQLParser().parseNormalizeQuery(queryToNormalize.getSourceString(), BASE_URI);
    final Map<String, Integer> valueConstants = new HashMap<>();
    final Set<String> subjectsAndObjects = new HashSet<String>();
    final Set<String> predicates = new HashSet<String>();
    final Set<String> predicateVariables = new HashSet<String>();
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(StatementPattern statementPattern) throws VisitorException {
            Var predicate = statementPattern.getPredicateVar();
            if (!predicate.isConstant() && !predicate.isAnonymous()) {
                predicateVariables.add(predicate.getName());
            }
            meetNode(statementPattern);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(ExtensionElem extensionElem) throws VisitorException {
            if (!predicateVariables.contains(extensionElem.getName())) {
                extensionElem.setExpr(normalizeValueExprHelper(extensionElem.getExpr(), valueConstants));
            }
            meetNode(extensionElem);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(BindingSetAssignment bindingSetAssignment) throws VisitorException {
            List<BindingSet> bindingSets = new ArrayList<BindingSet>();
            for (BindingSet bindingSet : bindingSetAssignment.getBindingSets()) {
                List<String> names = new ArrayList<String>();
                List<Value> values = new ArrayList<Value>();
                for (Binding binding : bindingSet) {
                    String name = binding.getName();
                    if (!predicateVariables.contains(name)) {
                        names.add(name);
                        values.add(normalizeValueHelper(binding.getValue(), valueConstants));
                    } else {
                        names.add(name);
                        values.add(binding.getValue());
                    }
                }
                bindingSets.add(new ListBindingSet(names, values));
            }
            bindingSetAssignment.setBindingSets(bindingSets);
            meetNode(bindingSetAssignment);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(StatementPattern statementPattern) throws VisitorException {
            statementPattern.setSubjectVar(normalizeSubjectsAndObjectsHelper(statementPattern.getSubjectVar(), valueConstants, subjectsAndObjects));
            statementPattern.setObjectVar(normalizeSubjectsAndObjectsHelper(statementPattern.getObjectVar(), valueConstants, subjectsAndObjects));
            try {
                String uri = getURI(statementPattern.getPredicateVar());
                predicates.add(uri);
            } catch (NoURIException e) {
            // NoURIException is used to notify us that there is no URI in this predicate, so we just don't add it.
            }
            // checkForVariable(statementPattern.getPredicateVar());
            meetNode(statementPattern);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(ArbitraryLengthPath arbitraryLengthPath) throws VisitorException {
            arbitraryLengthPath.setSubjectVar(normalizeSubjectsAndObjectsHelper(arbitraryLengthPath.getSubjectVar(), valueConstants, subjectsAndObjects));
            arbitraryLengthPath.setObjectVar(normalizeSubjectsAndObjectsHelper(arbitraryLengthPath.getObjectVar(), valueConstants, subjectsAndObjects));
            meetNode(arbitraryLengthPath);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(Compare compare) throws VisitorException {
            compare.setLeftArg(normalizeValueExprHelper(compare.getLeftArg(), valueConstants));
            compare.setRightArg(normalizeValueExprHelper(compare.getRightArg(), valueConstants));
            meetBinaryValueOperator(compare);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(IsLiteral isLiteral) throws VisitorException {
            isLiteral.setArg(normalizeValueExprHelper(isLiteral.getArg(), valueConstants));
            meetUnaryValueOperator(isLiteral);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(StatementPattern statementPattern) throws VisitorException {
            statementPattern.setSubjectVar(normalizeNonConstAnonymousHelper(statementPattern.getSubjectVar(), valueConstants));
            statementPattern.setObjectVar(normalizeNonConstAnonymousHelper(statementPattern.getObjectVar(), valueConstants));
            meetNode(statementPattern);
        }
    });
    this.setqIDs(subjectsAndObjects);
    this.setpIDs(predicates);
    return normalizedQuery;
}
Also used : ParsedQuery(org.openrdf.query.parser.ParsedQuery) NoURIException(utility.NoURIException) Binding(org.openrdf.query.Binding) BindingSet(org.openrdf.query.BindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) StandardizingSPARQLParser(openrdffork.StandardizingSPARQLParser) Value(org.openrdf.model.Value)

Example 2 with ListBindingSet

use of org.openrdf.query.impl.ListBindingSet in project incubator-rya by apache.

the class PipelineQueryIT method testFilterQuery.

@Test
public void testFilterQuery() throws Exception {
    // Insert data
    URI alice = VF.createURI("urn:Alice");
    URI bob = VF.createURI("urn:Bob");
    URI eve = VF.createURI("urn:Eve");
    URI relatedTo = VF.createURI("urn:relatedTo");
    insert(alice, FOAF.KNOWS, bob);
    insert(alice, FOAF.KNOWS, alice);
    insert(alice, FOAF.KNOWS, eve);
    insert(alice, relatedTo, bob);
    insert(bob, FOAF.KNOWS, eve);
    insert(bob, relatedTo, bob);
    dao.flush();
    // Define query 1 and expected results
    final String query1 = "SELECT * WHERE {\n" + "  ?x <" + FOAF.KNOWS.stringValue() + "> ?y1 .\n" + "  ?x <" + relatedTo.stringValue() + "> ?y2 .\n" + "  FILTER (?y1 != ?y2) .\n" + "}";
    final List<String> varNames = Arrays.asList("x", "y1", "y2");
    final Multiset<BindingSet> expected1 = HashMultiset.create();
    expected1.add(new ListBindingSet(varNames, alice, alice, bob));
    expected1.add(new ListBindingSet(varNames, alice, eve, bob));
    expected1.add(new ListBindingSet(varNames, bob, eve, bob));
    // Define query 2 and expected results
    final String query2 = "SELECT * WHERE {\n" + "  ?x <" + FOAF.KNOWS.stringValue() + "> ?y1 .\n" + "  ?x <" + relatedTo.stringValue() + "> ?y2 .\n" + "  FILTER (?y1 = ?y2) .\n" + "}";
    final Multiset<BindingSet> expected2 = HashMultiset.create();
    expected2.add(new ListBindingSet(varNames, alice, bob, bob));
    // Execute and verify results
    testPipelineQuery(query1, expected1);
    testPipelineQuery(query2, expected2);
}
Also used : QueryBindingSet(org.openrdf.query.algebra.evaluation.QueryBindingSet) BindingSet(org.openrdf.query.BindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) EmptyBindingSet(org.openrdf.query.impl.EmptyBindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) URI(org.openrdf.model.URI) Test(org.junit.Test)

Example 3 with ListBindingSet

use of org.openrdf.query.impl.ListBindingSet in project incubator-rya by apache.

the class InferenceIT method testHasValueValueQuery.

@Test
public void testHasValueValueQuery() throws Exception {
    final String ontology = "INSERT DATA { GRAPH <http://updated/test> {\n" + "  <urn:Hominid> owl:onProperty <urn:taxon> ; owl:hasValue <urn:Hominidae> . \n" + "  <urn:Carnivoran> owl:onProperty <urn:taxon>  ; owl:hasValue <urn:Carnivora> . \n" + "  <urn:Mammal> owl:onProperty <urn:taxon>  ; owl:hasValue <urn:Mammalia> . \n" + "  <urn:Tunicate> owl:onProperty <urn:taxon>  ; owl:hasValue <urn:Tunicata> . \n" + "  <urn:Person> rdfs:subClassOf <urn:Hominid> . \n" + "  <urn:Hominid> rdfs:subClassOf <urn:Mammal> . \n" + "  <urn:Cat> rdfs:subClassOf <urn:Carnivoran> . \n" + "  <urn:Carnivoran> rdfs:subClassOf <urn:Mammal> . \n" + "}}";
    final String instances = "INSERT DATA { GRAPH <http://updated/test> {\n" + "  <urn:Alice> a <urn:Person> . \n" + "  <urn:Bigfoot> a <urn:Mammal> . \n" + "  <urn:Carol> <urn:taxon> <urn:Hominidae> . \n" + "  <urn:Hank> a <urn:Cat> . \n" + "}}";
    final String query = "SELECT ?individual ?taxon { GRAPH <http://updated/test> { ?individual <urn:taxon> ?taxon } } \n";
    conn.prepareUpdate(QueryLanguage.SPARQL, ontology).execute();
    conn.prepareUpdate(QueryLanguage.SPARQL, instances).execute();
    inferenceEngine.refreshGraph();
    conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(resultHandler);
    final Set<BindingSet> expected = new HashSet<BindingSet>();
    final List<String> varNames = new LinkedList<>();
    varNames.add("individual");
    varNames.add("taxon");
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Alice"), vf.createURI("urn:Hominidae")));
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Alice"), vf.createURI("urn:Mammalia")));
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Bigfoot"), vf.createURI("urn:Mammalia")));
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Carol"), vf.createURI("urn:Hominidae")));
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Hank"), vf.createURI("urn:Carnivora")));
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Hank"), vf.createURI("urn:Mammalia")));
    Assert.assertEquals(expected, new HashSet<>(solutions));
}
Also used : BindingSet(org.openrdf.query.BindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 4 with ListBindingSet

use of org.openrdf.query.impl.ListBindingSet in project incubator-rya by apache.

the class InferenceIT method testHasSelfQuery.

@Test
public void testHasSelfQuery() throws Exception {
    final String ontology = "INSERT DATA { GRAPH <http://updated/test> {\n" + "  <urn:Narcissist> owl:onProperty <urn:love> ; owl:hasSelf \"true\" . \n" + "}}";
    final String instances = "INSERT DATA { GRAPH <http://updated/test> {\n" + "  <urn:Alice> a <urn:Narcissist> . \n" + "  <urn:Narcissus> <urn:love> <urn:Narcissus> . \n" + "}}";
    conn.prepareUpdate(QueryLanguage.SPARQL, ontology).execute();
    conn.prepareUpdate(QueryLanguage.SPARQL, instances).execute();
    inferenceEngine.refreshGraph();
    String query = "SELECT ?who ?self { GRAPH <http://updated/test> { ?self <urn:love> ?who } } \n";
    conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(resultHandler);
    final Set<BindingSet> expected = new HashSet<BindingSet>();
    final List<String> varNames = new LinkedList<>();
    varNames.add("who");
    varNames.add("self");
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Alice"), vf.createURI("urn:Alice")));
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Narcissus"), vf.createURI("urn:Narcissus")));
    Assert.assertEquals(expected, new HashSet<>(solutions));
    query = "SELECT ?self { GRAPH <http://updated/test> { <urn:Alice> <urn:love> ?self } } \n";
    conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(resultHandler);
    expected.clear();
    varNames.clear();
    varNames.add("self");
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Alice")));
    Assert.assertEquals(expected, new HashSet<>(solutions));
    query = "SELECT ?who { GRAPH <http://updated/test> { ?who <urn:love> <urn:Alice> } } \n";
    conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(resultHandler);
    expected.clear();
    varNames.clear();
    varNames.add("who");
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Alice")));
    Assert.assertEquals(expected, new HashSet<>(solutions));
    query = "SELECT ?who { GRAPH <http://updated/test> { ?who a <urn:Narcissist> } } \n";
    conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(resultHandler);
    expected.clear();
    varNames.clear();
    varNames.add("who");
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Narcissus")));
    expected.add(new ListBindingSet(varNames, vf.createURI("urn:Alice")));
    Assert.assertEquals(expected, new HashSet<>(solutions));
}
Also used : BindingSet(org.openrdf.query.BindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 5 with ListBindingSet

use of org.openrdf.query.impl.ListBindingSet in project incubator-rya by apache.

the class MongoSpinIT method testSailStrategy.

@Test
public void testSailStrategy() throws Exception {
    insertDataFile(Resources.getResource("data.ttl"), "http://example.org#");
    insertDataFile(Resources.getResource("university.ttl"), "http://example.org#");
    insertDataFile(Resources.getResource("owlrl.ttl"), "http://example.org#");
    Set<BindingSet> solutions = executeQuery(Resources.getResource("query.sparql"));
    Set<BindingSet> expected = new HashSet<>();
    Assert.assertEquals(expected, solutions);
    conf.setUseAggregationPipeline(false);
    ForwardChainSpinTool tool = new ForwardChainSpinTool();
    ToolRunner.run(conf, tool, new String[] {});
    solutions = executeQuery(Resources.getResource("query.sparql"));
    expected.add(new ListBindingSet(Arrays.asList("X", "Y"), VF.createURI(EX, "Alice"), VF.createURI(EX, "Department1")));
    Assert.assertEquals(expected, solutions);
    Assert.assertEquals(24, tool.getNumInferences());
}
Also used : BindingSet(org.openrdf.query.BindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

BindingSet (org.openrdf.query.BindingSet)16 ListBindingSet (org.openrdf.query.impl.ListBindingSet)16 Test (org.junit.Test)14 QueryBindingSet (org.openrdf.query.algebra.evaluation.QueryBindingSet)8 HashSet (java.util.HashSet)7 URI (org.openrdf.model.URI)7 EmptyBindingSet (org.openrdf.query.impl.EmptyBindingSet)7 LinkedList (java.util.LinkedList)5 QueryEvaluationException (org.openrdf.query.QueryEvaluationException)2 QueryRoot (org.openrdf.query.algebra.QueryRoot)2 HashMap (java.util.HashMap)1 StandardizingSPARQLParser (openrdffork.StandardizingSPARQLParser)1 Document (org.bson.Document)1 Value (org.openrdf.model.Value)1 Binding (org.openrdf.query.Binding)1 ParsedQuery (org.openrdf.query.parser.ParsedQuery)1 NoURIException (utility.NoURIException)1