Search in sources :

Example 11 with Union

use of org.openrdf.query.algebra.Union in project incubator-rya by apache.

the class DomainRangeVisitorTest method testRewriteTypePattern.

@Test
public void testRewriteTypePattern() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<URI> domainPredicates = new HashSet<>();
    final Set<URI> rangePredicates = new HashSet<>();
    domainPredicates.add(advisor);
    domainPredicates.add(takesCourse);
    rangePredicates.add(advisor);
    when(inferenceEngine.getPropertiesWithDomain(person)).thenReturn(domainPredicates);
    when(inferenceEngine.getPropertiesWithRange(person)).thenReturn(rangePredicates);
    final Var subjVar = new Var("s");
    final StatementPattern originalSP = new StatementPattern(subjVar, new Var("p", RDF.TYPE), new Var("o", person));
    final Projection query = new Projection(originalSP, new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new DomainRangeVisitor(conf, inferenceEngine));
    // Resulting tree should consist of Unions of:
    // 1. The original StatementPattern
    // 2. A join checking for domain inference
    // 3. A join checking for range inference
    boolean containsOriginal = false;
    boolean containsDomain = false;
    boolean containsRange = false;
    final Stack<TupleExpr> nodes = new Stack<>();
    nodes.push(query.getArg());
    while (!nodes.isEmpty()) {
        final TupleExpr currentNode = nodes.pop();
        if (currentNode instanceof Union) {
            nodes.push(((Union) currentNode).getLeftArg());
            nodes.push(((Union) currentNode).getRightArg());
        } else if (currentNode instanceof StatementPattern) {
            Assert.assertFalse(containsOriginal);
            Assert.assertEquals(originalSP, currentNode);
            containsOriginal = true;
        } else if (currentNode instanceof Join) {
            final TupleExpr left = ((Join) currentNode).getLeftArg();
            final TupleExpr right = ((Join) currentNode).getRightArg();
            Assert.assertTrue("Left-hand side should enumerate domain/range predicates", left instanceof FixedStatementPattern);
            Assert.assertTrue("Right-hand side should be a non-expandable SP matching triples satisfying domain/range", right instanceof DoNotExpandSP);
            final FixedStatementPattern fsp = (FixedStatementPattern) left;
            final StatementPattern sp = (StatementPattern) right;
            // fsp should be <predicate var, domain/range, original type var>
            boolean isDomain = RDFS.DOMAIN.equals(fsp.getPredicateVar().getValue());
            boolean isRange = RDFS.RANGE.equals(fsp.getPredicateVar().getValue());
            Assert.assertTrue(isDomain || isRange);
            Assert.assertEquals(originalSP.getObjectVar(), fsp.getObjectVar());
            // sp should have same predicate var
            Assert.assertEquals(fsp.getSubjectVar(), sp.getPredicateVar());
            // collect predicates that are enumerated in the FixedStatementPattern
            final Set<Resource> queryPredicates = new HashSet<>();
            for (Statement statement : fsp.statements) {
                queryPredicates.add(statement.getSubject());
            }
            if (isDomain) {
                Assert.assertFalse(containsDomain);
                // sp should be <original subject var, predicate var, unbound object var> for domain
                Assert.assertEquals(originalSP.getSubjectVar(), sp.getSubjectVar());
                Assert.assertFalse(sp.getObjectVar().hasValue());
                // verify predicates
                Assert.assertEquals(2, fsp.statements.size());
                Assert.assertEquals(domainPredicates, queryPredicates);
                Assert.assertTrue(queryPredicates.contains(advisor));
                Assert.assertTrue(queryPredicates.contains(takesCourse));
                containsDomain = true;
            } else {
                Assert.assertFalse(containsRange);
                // sp should be <unbound subject var, predicate var, original subject var> for range
                Assert.assertFalse(sp.getSubjectVar().hasValue());
                Assert.assertEquals(originalSP.getSubjectVar(), sp.getObjectVar());
                // verify predicates
                Assert.assertEquals(1, fsp.statements.size());
                Assert.assertEquals(rangePredicates, queryPredicates);
                Assert.assertTrue(queryPredicates.contains(advisor));
                containsRange = true;
            }
        } else {
            Assert.fail("Expected nested Unions of Joins and StatementPatterns, found: " + currentNode.toString());
        }
    }
    Assert.assertTrue(containsOriginal && containsDomain && containsRange);
}
Also used : ProjectionElemList(org.openrdf.query.algebra.ProjectionElemList) Var(org.openrdf.query.algebra.Var) Statement(org.openrdf.model.Statement) Resource(org.openrdf.model.Resource) Projection(org.openrdf.query.algebra.Projection) Join(org.openrdf.query.algebra.Join) URI(org.openrdf.model.URI) TupleExpr(org.openrdf.query.algebra.TupleExpr) Union(org.openrdf.query.algebra.Union) Stack(java.util.Stack) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) ProjectionElem(org.openrdf.query.algebra.ProjectionElem) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 12 with Union

use of org.openrdf.query.algebra.Union in project incubator-rya by apache.

the class HasValueVisitorTest method testRewriteTypePattern.

@Test
public void testRewriteTypePattern() throws Exception {
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    Map<URI, Set<Value>> vertebrateValues = new HashMap<>();
    vertebrateValues.put(hasCharacteristic, new HashSet<>());
    vertebrateValues.put(belongsTo, new HashSet<>());
    vertebrateValues.get(hasCharacteristic).add(notochord);
    vertebrateValues.get(hasCharacteristic).add(skull);
    vertebrateValues.get(belongsTo).add(chordata);
    when(inferenceEngine.getHasValueByType(vertebrate)).thenReturn(vertebrateValues);
    // Query for a specific type and rewrite using the visitor:
    final Projection query = new Projection(new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", vertebrate)), new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasValueVisitor(conf, inferenceEngine));
    // Expected structure: two nested unions whose members are (in some order) the original
    // statement pattern and two joins, one for each unique property involved in a relevant
    // restriction. Each join should be between a StatementPattern for the property and a
    // FixedStatementPattern providing the value(s).
    // Collect the arguments to the unions, ignoring nesting order:
    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union1 = (Union) query.getArg();
    final Set<TupleExpr> unionArgs = new HashSet<>();
    if (union1.getLeftArg() instanceof Union) {
        unionArgs.add(((Union) union1.getLeftArg()).getLeftArg());
        unionArgs.add(((Union) union1.getLeftArg()).getRightArg());
        unionArgs.add(union1.getRightArg());
    } else {
        Assert.assertTrue(union1.getRightArg() instanceof Union);
        unionArgs.add(union1.getLeftArg());
        unionArgs.add(((Union) union1.getRightArg()).getLeftArg());
        unionArgs.add(((Union) union1.getRightArg()).getRightArg());
    }
    // There should be one StatementPattern and two joins with structure Join(FSP, SP):
    final StatementPattern directSP = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", vertebrate));
    StatementPattern actualSP = null;
    FixedStatementPattern hasCharacteristicFSP = null;
    FixedStatementPattern belongsToFSP = null;
    for (TupleExpr arg : unionArgs) {
        if (arg instanceof StatementPattern) {
            actualSP = (StatementPattern) arg;
        } else {
            Assert.assertTrue(arg instanceof Join);
            final Join join = (Join) arg;
            Assert.assertTrue(join.getLeftArg() instanceof FixedStatementPattern);
            Assert.assertTrue(join.getRightArg() instanceof StatementPattern);
            final FixedStatementPattern fsp = (FixedStatementPattern) join.getLeftArg();
            final StatementPattern sp = (StatementPattern) join.getRightArg();
            // Should join FSP([unused], property, ?value) with SP(subject, property, ?value)
            Assert.assertEquals(directSP.getSubjectVar(), sp.getSubjectVar());
            Assert.assertEquals(fsp.getPredicateVar(), sp.getPredicateVar());
            Assert.assertEquals(fsp.getObjectVar(), sp.getObjectVar());
            if (hasCharacteristic.equals(fsp.getPredicateVar().getValue())) {
                hasCharacteristicFSP = fsp;
            } else if (belongsTo.equals(fsp.getPredicateVar().getValue())) {
                belongsToFSP = fsp;
            } else {
                Assert.fail("Unexpected property variable in rewritten query: " + fsp.getPredicateVar());
            }
        }
    }
    Assert.assertEquals(directSP, actualSP);
    Assert.assertNotNull(hasCharacteristicFSP);
    Assert.assertNotNull(belongsToFSP);
    // Verify the expected FSPs for the appropriate properties:
    Assert.assertEquals(2, hasCharacteristicFSP.statements.size());
    Assert.assertTrue(hasCharacteristicFSP.statements.contains(vf.createStatement(vertebrate, hasCharacteristic, skull)));
    Assert.assertTrue(hasCharacteristicFSP.statements.contains(vf.createStatement(vertebrate, hasCharacteristic, notochord)));
    Assert.assertEquals(1, belongsToFSP.statements.size());
    Assert.assertTrue(belongsToFSP.statements.contains(vf.createStatement(vertebrate, belongsTo, chordata)));
}
Also used : ProjectionElemList(org.openrdf.query.algebra.ProjectionElemList) HashSet(java.util.HashSet) Set(java.util.Set) HasValueVisitor(org.apache.rya.rdftriplestore.inference.HasValueVisitor) HashMap(java.util.HashMap) Var(org.openrdf.query.algebra.Var) Projection(org.openrdf.query.algebra.Projection) Join(org.openrdf.query.algebra.Join) URI(org.openrdf.model.URI) Union(org.openrdf.query.algebra.Union) TupleExpr(org.openrdf.query.algebra.TupleExpr) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) InferenceEngine(org.apache.rya.rdftriplestore.inference.InferenceEngine) ProjectionElem(org.openrdf.query.algebra.ProjectionElem) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 13 with Union

use of org.openrdf.query.algebra.Union in project incubator-rya by apache.

the class InverseOfVisitor method meetSP.

@Override
protected void meetSP(StatementPattern node) throws Exception {
    StatementPattern sp = node.clone();
    final Var predVar = sp.getPredicateVar();
    URI pred = (URI) predVar.getValue();
    String predNamespace = pred.getNamespace();
    final Var objVar = sp.getObjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (objVar != null && !RDF.NAMESPACE.equals(predNamespace) && !SESAME.NAMESPACE.equals(predNamespace) && !RDFS.NAMESPACE.equals(predNamespace) && !EXPANDED.equals(cntxtVar)) {
        /**
         * { ?a ?pred ?b .}\n" +
         *             "       UNION " +
         *             "      { ?b ?pred ?a }
         */
        URI predUri = (URI) predVar.getValue();
        URI invPropUri = inferenceEngine.findInverseOf(predUri);
        if (invPropUri != null) {
            Var subjVar = sp.getSubjectVar();
            Union union = new InferUnion();
            union.setLeftArg(sp);
            union.setRightArg(new StatementPattern(objVar, new Var(predVar.getName(), invPropUri), subjVar, cntxtVar));
            node.replaceWith(union);
        }
    }
}
Also used : StatementPattern(org.openrdf.query.algebra.StatementPattern) Var(org.openrdf.query.algebra.Var) URI(org.openrdf.model.URI) Union(org.openrdf.query.algebra.Union)

Aggregations

StatementPattern (org.openrdf.query.algebra.StatementPattern)13 Union (org.openrdf.query.algebra.Union)13 Var (org.openrdf.query.algebra.Var)13 Test (org.junit.Test)10 Projection (org.openrdf.query.algebra.Projection)10 ProjectionElem (org.openrdf.query.algebra.ProjectionElem)10 ProjectionElemList (org.openrdf.query.algebra.ProjectionElemList)10 Resource (org.openrdf.model.Resource)8 HashSet (java.util.HashSet)7 Set (java.util.Set)6 URI (org.openrdf.model.URI)6 Join (org.openrdf.query.algebra.Join)6 TupleExpr (org.openrdf.query.algebra.TupleExpr)6 HashMap (java.util.HashMap)5 FixedStatementPattern (org.apache.rya.rdftriplestore.utils.FixedStatementPattern)5 NullableStatementImpl (org.apache.rya.api.utils.NullableStatementImpl)2 HasValueVisitor (org.apache.rya.rdftriplestore.inference.HasValueVisitor)2 InferenceEngine (org.apache.rya.rdftriplestore.inference.InferenceEngine)2 Statement (org.openrdf.model.Statement)2 Extension (org.openrdf.query.algebra.Extension)2