org.eclipse.rdf4j.query.algebra.Projection Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.Projection. 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: SPARQLParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verify that an INSERT with a subselect using a wildcard correctly adds vars to projection
 *
 * @see <a href="https://github.com/eclipse/rdf4j/issues/686">#686</a>
 */
@Test
public void testParseWildcardSubselectInUpdate() throws Exception {
	StringBuilder update = new StringBuilder();
	update.append("INSERT { <urn:a> <urn:b> <urn:c> . } WHERE { SELECT * {?s ?p ?o } }");

	ParsedUpdate parsedUpdate = parser.parseUpdate(update.toString(), null);
	List<UpdateExpr> exprs = parsedUpdate.getUpdateExprs();
	assertEquals(1, exprs.size());

	UpdateExpr expr = exprs.get(0);
	assertTrue(expr instanceof Modify);
	Modify m = (Modify) expr;
	TupleExpr whereClause = m.getWhereExpr();
	assertTrue(whereClause instanceof Projection);
	ProjectionElemList projectionElemList = ((Projection) whereClause).getProjectionElemList();
	assertNotNull(projectionElemList);
	List<ProjectionElem> elements = projectionElemList.getElements();
	assertNotNull(elements);

	assertEquals("projection should contain all three variables", 3, elements.size());
}
 
Example #2
Source File: OneOfVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testOneOfDisabled() throws Exception {
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isEnumeratedType(SUITS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(SUITS)).thenReturn(CARD_SUIT_ENUMERATION);
    when(inferenceEngine.isEnumeratedType(RANKS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(RANKS)).thenReturn(CARD_RANK_ENUMERATION);

    // Query for a Suits and rewrite using the visitor:
    final Projection query = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", SUITS)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));

    final AccumuloRdfConfiguration disabledConf = conf.clone();
    disabledConf.setInferOneOf(false);

    query.visit(new OneOfVisitor(disabledConf, inferenceEngine));

    // Expected structure: the original statement:
    assertTrue(query.getArg() instanceof StatementPattern);
    final StatementPattern actualCardSuitSp = (StatementPattern) query.getArg();
    final StatementPattern expectedCardSuitSp = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", SUITS));
    assertEquals(expectedCardSuitSp, actualCardSuitSp);
}
 
Example #3
Source File: TopologyFactory.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final Projection node) throws TopologyBuilderException {
    final String id = PROJECTION_PREFIX + UUID.randomUUID();
    final Optional<Side> side = getSide(node);

    // If the arg is an Extension, there are rebindings that need to be
    // ignored since they do not have a processor node.
    TupleExpr downstreamNode = node.getArg();
    if (downstreamNode instanceof Extension) {
        downstreamNode = ((Extension) downstreamNode).getArg();
    }

    final ProjectionProcessorSupplier supplier = new ProjectionProcessorSupplier(
            ProjectionEvaluator.make(node),
            result -> getResult(side, result));

    entries.add(new ProcessorEntry(node, id, side, supplier, Lists.newArrayList(downstreamNode)));
    idMap.put(node, id);
    super.meet(node);
}
 
Example #4
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Projection visitResultVariables(Resource resultVars, Map<String, ProjectionElem> previousProjElems)
		throws RDF4JException {
	ProjectionElemList projElemList = new ProjectionElemList();
	Iteration<Resource, QueryEvaluationException> iter = TripleSources.listResources(resultVars,
			store);
	while (iter.hasNext()) {
		Resource r = iter.next();
		ProjectionElem projElem = visitResultVariable(r, previousProjElems);
		projElemList.addElement(projElem);
	}

	Projection proj = new Projection();
	proj.setProjectionElemList(projElemList);

	tupleRoot = proj;
	return proj;
}
 
Example #5
Source File: SparqlToPigTransformVisitor.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(Projection node) throws RuntimeException {
    super.meet(node);
    ProjectionElemList list = node.getProjectionElemList();
    String set = null;
    StringBuilder projList = new StringBuilder();
    boolean first = true;
    //TODO: we do not support projections from multiple pig statements yet
    for (String name : list.getTargetNames()) {
        set = varToSet.get(name);  //TODO: overwrite
        if (set == null) {
            throw new IllegalArgumentException("Have not found any pig logic for name[" + name + "]");
        }
        if (!first) {
            projList.append(",");
        }
        first = false;
        projList.append(name);
    }
    if (set == null)
        throw new IllegalArgumentException(""); //TODO: Fill this
    //SUBORG = FOREACH SUBORG_L GENERATE dept, univ;
    pigScriptBuilder.append("PROJ = FOREACH ").append(set).append(" GENERATE ").append(projList.toString()).append(";\n");
}
 
Example #6
Source File: HasSelfVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypePattern() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<IRI> narcissistProps = new HashSet<>();
    narcissistProps.add(love);
    when(inferenceEngine.getHasSelfImplyingType(narcissist)).thenReturn(narcissistProps);
    final Var subj = new Var("s");
    final Var obj = new Var("o", narcissist);
    obj.setConstant(true);
    final Var pred = new Var("p", RDF.TYPE);
    pred.setConstant(true);

    final Projection query = new Projection(new StatementPattern(subj, pred, obj),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasSelfVisitor(conf, inferenceEngine));

    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union = (Union) query.getArg();
    Assert.assertTrue(union.getRightArg() instanceof StatementPattern);
    Assert.assertTrue(union.getLeftArg() instanceof StatementPattern);
    final StatementPattern expectedLeft = new StatementPattern(subj, pred, obj);
    final StatementPattern expectedRight = new StatementPattern(subj, new Var("urn:love", love), subj);
    Assert.assertEquals(expectedLeft, union.getLeftArg());
    Assert.assertEquals(expectedRight, union.getRightArg());
}
 
Example #7
Source File: ProjectionEvaluatorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * This Projection enumerates all of the variables that were in the query, none of them are anonymous, and
 * none of them insert constants.
 */
@Test
public void changesNothing() throws Exception {
    // Read the projection object from a SPARQL query.
    final Projection projection = getProjection(
            "SELECT ?person ?employee ?business " +
            "WHERE { " +
                "?person <urn:talksTo> ?employee . " +
                "?employee <urn:worksAt> ?business . " +
            "}");

    // Create a Binding Set that contains the result of the WHERE clause.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final MapBindingSet bs = new MapBindingSet();
    bs.addBinding("person", vf.createIRI("urn:Alice"));
    bs.addBinding("employee", vf.createIRI("urn:Bob"));
    bs.addBinding("business", vf.createIRI("urn:TacoJoint"));
    final VisibilityBindingSet original = new VisibilityBindingSet(bs, "a|b");

    // Execute the projection.
    final VisibilityBindingSet result = ProjectionEvaluator.make(projection).project(original);
    assertEquals(original, result);
}
 
Example #8
Source File: ReflexivePropertyVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testReflexiveProperty() throws Exception {
    // Define a reflexive property
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isReflexiveProperty(HAS_FAMILY)).thenReturn(true);
    // Construct a query, then visit it
    final StatementPattern sp = new StatementPattern(new Var("s", ALICE), new Var("p", HAS_FAMILY), new Var("o"));
    final Projection query = new Projection(sp, new ProjectionElemList(new ProjectionElem("o", "member")));
    query.visit(new ReflexivePropertyVisitor(conf, inferenceEngine));
    // Expected structure after rewriting SP(:Alice :hasFamilyMember ?member):
    //
    // Union(
    //     originalSP(:Alice :hasFamilyMember ?member),
    //     ZeroLengthPath(:Alice, ?member)
    // )
    Assert.assertTrue(query.getArg() instanceof Union);
    final TupleExpr left = ((Union) query.getArg()).getLeftArg();
    final TupleExpr right = ((Union) query.getArg()).getRightArg();
    Assert.assertEquals(sp, left);
    Assert.assertTrue(right instanceof ZeroLengthPath);
    Assert.assertEquals(sp.getSubjectVar(), ((ZeroLengthPath) right).getSubjectVar());
    Assert.assertEquals(sp.getObjectVar(), ((ZeroLengthPath) right).getObjectVar());
}
 
Example #9
Source File: SimpleExternalTupleSetTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void equals_equals() throws MalformedQueryException {
    // The common PCJ expression.
    final String sparql =
            "SELECT ?f ?m ?d { " +
                "?f <urn:talksTo> ?m . " +
                "?m <uri:associatesWith> ?d . " +
            "}";

    final ParsedQuery query = new SPARQLParser().parseQuery(sparql, null);
    final Projection pcjExpression = (Projection) query.getTupleExpr();

    // Create two SimpleExternalTupleSet pbjects using the same expression.
    final SimpleExternalTupleSet testSet = new SimpleExternalTupleSet(pcjExpression);
    final SimpleExternalTupleSet identicalTestSet = new SimpleExternalTupleSet(pcjExpression);

    // Show that they are equal.
    assertEquals(testSet, identicalTestSet);
}
 
Example #10
Source File: TupleExprs.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verifies if the supplied {@link TupleExpr} contains a {@link Projection}. If the supplied TupleExpr is a
 * {@link Join} or contains a {@link Join}, projections inside that Join's arguments will not be taken into account.
 *
 * @param t a tuple expression.
 * @return <code>true</code> if the TupleExpr contains a projection (outside of a Join), <code>false</code>
 *         otherwise.
 * @deprecated since 2.0. Use {@link #containsSubquery(TupleExpr)} instead.
 */
@Deprecated
public static boolean containsProjection(TupleExpr t) {
	Deque<TupleExpr> queue = new ArrayDeque<>();
	queue.add(t);
	while (!queue.isEmpty()) {
		TupleExpr n = queue.removeFirst();
		if (n instanceof Projection) {
			return true;
		} else if (n instanceof Join) {
			// projections already inside a Join need not be
			// taken into account
			return false;
		} else {
			queue.addAll(getChildren(n));
		}
	}
	return false;
}
 
Example #11
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Construct a SELECT query for a grouped bound check.
 *
 * Pattern:
 *
 * SELECT DISTINCT ?o_1 .. ?o_N WHERE { { s1 p1 ?o_1 FILTER ?o_1=o1 } UNION ... UNION { sN pN ?o_N FILTER ?o_N=oN }}
 *
 * @param stmt
 * @param unionBindings
 * @return the SELECT query
 */
public static TupleExpr selectQueryStringBoundCheck(StatementPattern stmt, List<BindingSet> unionBindings) {

	Set<String> varNames = new HashSet<>();

	Union union = new Union();
	union.setLeftArg(constructStatementCheckId(stmt, 0, varNames, unionBindings.get(0)));
	Union tmp = union;
	int idx;
	for (idx = 1; idx < unionBindings.size() - 1; idx++) {
		Union _u = new Union();
		_u.setLeftArg(constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)));
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg(constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)));

	ProjectionElemList projList = new ProjectionElemList();
	for (String var : varNames) {
		projList.addElement(new ProjectionElem(var));
	}

	Projection proj = new Projection(union, projList);

	return proj;
}
 
Example #12
Source File: TestPropPathMisbehaviour.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * reproduces GH-2343: the obj var of the nested statement pattern should be equal to the objVar of the ALP path
 * that is using the PE
 */
@Test
public void testGH2343() {
	String query1 = "select ?iri ?value where { \n" +
			"    ?iri (<urn:p>+) / <urn:q> ?value .\n" +
			"}";
	ParsedQuery q = parser.parseQuery(query1, "http://base.org/");

	assertNotNull(q);
	assertTrue("expect projection", q.getTupleExpr() instanceof Projection);
	Projection proj = (Projection) q.getTupleExpr();

	assertTrue("expect join", proj.getArg() instanceof Join);
	assertTrue("expect left arg to be ALP", ((Join) proj.getArg()).getLeftArg() instanceof ArbitraryLengthPath);
	ArbitraryLengthPath alp = (ArbitraryLengthPath) ((Join) proj.getArg()).getLeftArg();

	assertTrue("expect single statement pattern in alp PE", alp.getPathExpression() instanceof StatementPattern);
	StatementPattern sp = (StatementPattern) alp.getPathExpression();
	assertNotNull(sp.getSubjectVar());

	assertTrue("expect subj var to be iri", "iri".equals(sp.getSubjectVar().getName()));

	assertTrue("expect obj var of the pattern to be same as the objVar of ALP",
			alp.getObjectVar().equals(sp.getObjectVar()));
}
 
Example #13
Source File: PCJNodeConsolidatorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwitchBoundVars() throws Exception {

	String query1 = ""//
			+ "SELECT ?a ?b " //
			+ "{" //
			+ "  ?a <uri:p0> ?b ." //
			+ " OPTIONAL{ ?a <uri:p1> <uri:o1> } ." //
			+ " ?a <uri:p2> <uri:o2> " //
			+ "}";//

	String query2 = ""//
			+ "SELECT ?a ?b " //
			+ "{" //
			+ " ?a <uri:p2> <uri:o2> " //
			+ " OPTIONAL{ ?a <uri:p1> <uri:o1> } ." //
			+ "  ?a <uri:p0> ?b ." //
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	Join join1 = (Join) ((Projection) te1).getArg();
	Join join2 = (Join) ((Projection) te2).getArg();

	QuerySegment<ExternalTupleSet> seg1 = qFactory.getQuerySegment(join1);
    QuerySegment<ExternalTupleSet> seg2 = qFactory.getQuerySegment(join2);

	QueryNodeConsolidator consolidator = new QueryNodeConsolidator(seg1.getOrderedNodes(), seg2.getOrderedNodes());
	List<QueryModelNode> queryNodes = new ArrayList<>(seg2.getOrderedNodes());

	Assert.assertTrue(consolidator.consolidateNodes());
	Assert.assertEquals(consolidator.getQueryNodes(), queryNodes);
}
 
Example #14
Source File: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyProjection() throws Exception {
    StatementPattern isClass = new StatementPattern(constant(UNDERGRAD), constant(RDF.TYPE), constant(OWL.CLASS));
    QueryRoot queryTree = new QueryRoot(new Projection(isClass, new ProjectionElemList()));
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof Projection);
    Projection projectNode = (Projection) queryTree.getArg();
    Assert.assertTrue(projectNode.getArg() instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) projectNode.getArg();
    Assert.assertEquals(Sets.newHashSet(), pipelineNode.getAssuredBindingNames());
}
 
Example #15
Source File: IndexedExecutionPlanGeneratorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrowsException2() throws Exception {

	SPARQLParser parser = new SPARQLParser();

	ParsedQuery pq1 = parser.parseQuery(q19, null);
	ParsedQuery pq2 = parser.parseQuery(q20, null);

	SimpleExternalTupleSet extTup1 = new SimpleExternalTupleSet(
			(Projection) pq2.getTupleExpr());

	List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>();

	list.add(extTup1);

	IndexedExecutionPlanGenerator iep = new IndexedExecutionPlanGenerator(
			pq1.getTupleExpr(), list);
	List<ExternalTupleSet> indexSet = iep.getNormalizedIndices();
	Assert.assertEquals(3, indexSet.size());

	Iterator<TupleExpr> processedTups = iep.getIndexedTuples();

	processedTups.next();
	processedTups.next();
	processedTups.next();

	boolean exceptionThrown = false;
	try {
		processedTups.next();
	} catch (NoSuchElementException e) {
		exceptionThrown = true;
	}

	Assert.assertTrue(exceptionThrown);

}
 
Example #16
Source File: FilterSerializerTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void nowTest() throws Exception {

    //tests to see if NOW function is correctly serialized and deserialized
    //by FilterSerializer
    String query = "select * {Filter(NOW())}";
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    Filter filter = (Filter) ((Projection) pq.getTupleExpr()).getArg();
    String filterString = FilterSerializer.serialize(filter);
    Filter deserializedFilter = FilterSerializer.deserialize(filterString);
    
    assertEquals(filter, deserializedFilter);

}
 
Example #17
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingVariables() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new ValueConstant(FOAF.PERSON), "x"),
            new ExtensionElem(new ValueConstant(RDF.TYPE), "y"));
    Projection projection = new Projection(extension, new ProjectionElemList(
            new ProjectionElem("x", "s"),
            new ProjectionElem("y", "predicate"),
            new ProjectionElem("z", "object")));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(null), p(RDF.TYPE), o(null)));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #18
Source File: ProjectionProcessorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void showProjectionFunctionIsCalled() throws Exception {
    // A query whose projection does not change anything.
    final Projection projection = RdfTestUtil.getProjection(
            "SELECT (?person AS ?p) (?employee AS ?e) ?business " +
            "WHERE { " +
                "?person <urn:talksTo> ?employee . " +
                "?employee <urn:worksAt> ?business . " +
            "}");

    // Create a Binding Set that contains the result of the WHERE clause.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final MapBindingSet inputBs = new MapBindingSet();
    inputBs.addBinding("person", vf.createIRI("urn:Alice"));
    inputBs.addBinding("employee", vf.createIRI("urn:Bob"));
    inputBs.addBinding("business", vf.createIRI("urn:TacoJoint"));
    final VisibilityBindingSet inputVisBs = new VisibilityBindingSet(inputBs, "a");

    // The expected binding set changes the "person" binding name to "p" and "employee" to "e".
    final MapBindingSet expectedBs = new MapBindingSet();
    expectedBs.addBinding("p", vf.createIRI("urn:Alice"));
    expectedBs.addBinding("e", vf.createIRI("urn:Bob"));
    expectedBs.addBinding("business", vf.createIRI("urn:TacoJoint"));
    final VisibilityBindingSet expectedVisBs = new VisibilityBindingSet(expectedBs, "a");

    // Show it resulted in the correct output BindingSet.
    final ProcessorContext context = mock(ProcessorContext.class);
    final ProjectionProcessor processor = new ProjectionProcessor(
            ProjectionEvaluator.make(projection),
            result -> ProcessorResult.make(new UnaryResult(result)));
    processor.init(context);

    processor.process("key", ProcessorResult.make(new UnaryResult(inputVisBs)));

    // Verify the expected binding set was emitted.
    final ProcessorResult expected = ProcessorResult.make(new UnaryResult(expectedVisBs));
    verify(context, times(1)).forward(eq("key"), eq(expected));
}
 
Example #19
Source File: PCJOptimizerTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testJoinMatcherRejectsLeftJoinPcj() throws Exception {

    final String query1 = ""//
            + "SELECT ?e ?c ?l" //
            + "{" //
            + "  ?e a ?c . "//
            + "  ?e <uri:talksTo> ?l . "//
            + "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l "//
            + "}";//

    final String query2 = ""//
            + "SELECT ?a ?b ?m" //
            + "{" //
            + "  ?a a ?b . "//
            + "  ?a <uri:talksTo> ?m . "//
            + "  OPTIONAL {?a <http://www.w3.org/2000/01/rdf-schema#label> ?m}  . "//
            + "}";//

    final SPARQLParser parser = new SPARQLParser();
    final ParsedQuery pq1 = parser.parseQuery(query1, null);
    final ParsedQuery pq2 = parser.parseQuery(query2, null);
    final TupleExpr te1 = pq1.getTupleExpr();
    final TupleExpr te2 = pq2.getTupleExpr();
    final TupleExpr expected = te1.clone();

    final SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection) te2);
    final List<ExternalTupleSet> externalList = new ArrayList<>();
    externalList.add(pcj);

    provider.setIndices(externalList);
    final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
    optimizer.optimize(te1, null, null);
    Assert.assertEquals(expected, te1);

}
 
Example #20
Source File: MatcherUtilities.java    From rya with Apache License 2.0 5 votes vote down vote up
public static boolean segmentContainsLeftJoins(final TupleExpr tupleExpr) {
    if (tupleExpr instanceof Projection) {
        return segmentContainsLeftJoins(((Projection) tupleExpr).getArg());
    } else if (tupleExpr instanceof Join) {
        final Join join = (Join) tupleExpr;
        return segmentContainsLeftJoins(join.getRightArg())
                || segmentContainsLeftJoins(join.getLeftArg());
    } else if (tupleExpr instanceof LeftJoin) {
        return true;
    } else if (tupleExpr instanceof Filter) {
        return segmentContainsLeftJoins(((Filter) tupleExpr).getArg());
    } else {
        return false;
    }
}
 
Example #21
Source File: GeneralizedExternalProcessor.java    From rya with Apache License 2.0 5 votes vote down vote up
public SubsetEqualsVisitor(ExternalTupleSet index, TupleExpr query) {
    this.tuple = index.getTupleExpr();
    this.set = index;
    indexQNode = ((Projection) tuple).getArg();
    sSet = getQNodes(indexQNode);

}
 
Example #22
Source File: IndexedExecutionPlanGeneratorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrowsException1() throws Exception {

	SPARQLParser parser = new SPARQLParser();

	ParsedQuery pq1 = parser.parseQuery(q16, null);
	ParsedQuery pq2 = parser.parseQuery(q17, null);
	ParsedQuery pq3 = parser.parseQuery(q18, null);

	SimpleExternalTupleSet extTup1 = new SimpleExternalTupleSet(
			(Projection) pq2.getTupleExpr());
	SimpleExternalTupleSet extTup2 = new SimpleExternalTupleSet(
			(Projection) pq3.getTupleExpr());

	List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>();

	list.add(extTup2);
	list.add(extTup1);

	IndexedExecutionPlanGenerator iep = new IndexedExecutionPlanGenerator(
			pq1.getTupleExpr(), list);
	List<ExternalTupleSet> indexSet = iep.getNormalizedIndices();
	Assert.assertEquals(6, indexSet.size());

	Iterator<TupleExpr> processedTups = iep.getIndexedTuples();

	boolean exceptionThrown = false;

	try {
		processedTups.remove();
	} catch (UnsupportedOperationException e) {
		exceptionThrown = true;
	}

	Assert.assertTrue(exceptionThrown);

}
 
Example #23
Source File: PCJNodeConsolidatorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlreadyInOrder() throws Exception {

	String query1 = ""//
			+ "SELECT ?a ?b ?c ?d" //
			+ "{" //
			+ "  ?a <uri:p5> <uri:const3>" //
			+ "  OPTIONAL{?a <uri:p3> ?c} . " //
			+ "  ?a <uri:p4> ?b . "//
			+ "  OPTIONAL{<uri:const2> <uri:p4> ?d } . "//
			+ "  ?c <uri:p1> ?d "
			+ "  OPTIONAL{<uri:const1> <uri:p2> ?b} . "//
			+ "}";//

	String query2 = ""//
			+ "SELECT ?a ?b ?c ?d" //
			+ "{" //
			+ "  ?a <uri:p4> ?b . "//
			+ "  OPTIONAL{<uri:const2> <uri:p4> ?d } . "//
			+ "  ?c <uri:p1> ?d "
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	LeftJoin join1 = (LeftJoin) ((Projection) te1).getArg();
	Join join2 = (Join) ((Projection) te2).getArg();

	QuerySegment<ExternalTupleSet> seg1 = qFactory.getQuerySegment(join1);
       QuerySegment<ExternalTupleSet> seg2 = qFactory.getQuerySegment(join2);

	QueryNodeConsolidator consolidator = new QueryNodeConsolidator(seg1.getOrderedNodes(), seg2.getOrderedNodes());
	List<QueryModelNode> queryNodes = new ArrayList<>(seg1.getOrderedNodes());

	Assert.assertTrue(consolidator.consolidateNodes());
	Assert.assertEquals(consolidator.getQueryNodes(), queryNodes);

}
 
Example #24
Source File: OneOfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneOf() throws Exception {
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isEnumeratedType(SUITS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(SUITS)).thenReturn(CARD_SUIT_ENUMERATION);
    when(inferenceEngine.isEnumeratedType(RANKS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(RANKS)).thenReturn(CARD_RANK_ENUMERATION);
    // Query for a  Suits and rewrite using the visitor:
    final Projection query = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", SUITS)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new OneOfVisitor(conf, inferenceEngine));
    // Expected structure: BindingSetAssignment containing the enumeration:
    // BindingSetAssignment(CLUBS, DIAMONDS, HEARTS, SPADES)
    // Collect the arguments to the BindingSetAssignment:
    assertTrue(query.getArg() instanceof BindingSetAssignment);
    final BindingSetAssignment bsa = (BindingSetAssignment) query.getArg();
    final Iterable<BindingSet> iterable = bsa.getBindingSets();
    final Iterator<BindingSet> iter = iterable.iterator();

    assertBindingSet(iter, CARD_SUIT_ENUMERATION.iterator());

    // Query for a Ranks and rewrite using the visitor:
    final Projection query2 = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", RANKS)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query2.visit(new OneOfVisitor(conf, inferenceEngine));
    // Expected structure: BindingSetAssignment containing the enumeration:
    // BindingSetAssignment(ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, JACK, QUEEN, KING)
    // Collect the arguments to the BindingSetAssignment:
    assertTrue(query2.getArg() instanceof BindingSetAssignment);
    final BindingSetAssignment bsa2 = (BindingSetAssignment) query2.getArg();
    final Iterable<BindingSet> iterable2 = bsa2.getBindingSets();
    final Iterator<BindingSet> iter2 = iterable2.iterator();

    assertBindingSet(iter2, CARD_RANK_ENUMERATION.iterator());
}
 
Example #25
Source File: HasSelfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyPattern_constantObj() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<Resource> loveTypes = new HashSet<>();
    loveTypes.add(narcissist);
    when(inferenceEngine.getHasSelfImplyingProperty(love)).thenReturn(loveTypes);
    final Var subj = new Var("s");
    final Var obj = new Var("o", self);
    obj.setConstant(true);
    final Var pred = new Var("p", love);
    pred.setConstant(true);

    final Projection query = new Projection(new StatementPattern(subj, pred, obj),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasSelfVisitor(conf, inferenceEngine));

    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union = (Union) query.getArg();
    Assert.assertTrue(union.getRightArg() instanceof StatementPattern);
    Assert.assertTrue(union.getLeftArg() instanceof Extension);
    final StatementPattern expectedRight = new StatementPattern(subj, pred, obj);
    final Extension expectedLeft = new Extension(
            new StatementPattern(obj, new Var(RDF.TYPE.stringValue(), RDF.TYPE), new Var("urn:Narcissist", narcissist)),
            new ExtensionElem(obj, "s"));
    Assert.assertEquals(expectedLeft, union.getLeftArg());
    Assert.assertEquals(expectedRight, union.getRightArg());
}
 
Example #26
Source File: SimpleExternalTupleSetTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void equals_notEquals() throws MalformedQueryException {
    // Create the first SimpleExternalTupleSet object.
    final String sparql1 =
            "SELECT ?f ?m ?d { " +
                "?f <urn:talksTo> ?m . " +
                "?m <uri:associatesWith> ?d . " +
            "}";

    final ParsedQuery query1 = new SPARQLParser().parseQuery(sparql1, null);
    final Projection pcjExpression1 = (Projection) query1.getTupleExpr();
    final SimpleExternalTupleSet set1 = new SimpleExternalTupleSet(pcjExpression1);

    // Create another one using a different expression.
    final String sparql2 =
            "SELECT ?f ?m ?d { " +
                "?f <urn:talksTo> ?m . " +
                "?m <uri:friendsWith> ?d . " +
            "}";

    final ParsedQuery query2 = new SPARQLParser().parseQuery(sparql2, null);
    final Projection pcjExpression2 = (Projection) query2.getTupleExpr();
    final SimpleExternalTupleSet set2 = new SimpleExternalTupleSet(pcjExpression2);

    // Show they are not equal.
    assertNotEquals(set1, set2);
}
 
Example #27
Source File: RdfCloudTripleStoreEvaluationStatistics.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void meetUnaryTupleOperator(final UnaryTupleOperator node) {
    if (node instanceof Projection) {
        cardinality += -1.0;
    }
    super.meetUnaryTupleOperator(node);
}
 
Example #28
Source File: HalyardTupleExprEvaluation.java    From Halyard with Apache License 2.0 5 votes vote down vote up
/**
 * Switch logic for evaluation of any instance of a {@link UnaryTupleOperator} query model node
 * @param parent
 * @param expr
 * @param bindings
 */
private void evaluateUnaryTupleOperator(BindingSetPipe parent, UnaryTupleOperator expr, BindingSet bindings) {
    if (expr instanceof Projection) {
        evaluateProjection(parent, (Projection) expr, bindings);
    } else if (expr instanceof MultiProjection) {
        evaluateMultiProjection(parent, (MultiProjection) expr, bindings);
    } else if (expr instanceof Filter) {
        evaluateFilter(parent, (Filter) expr, bindings);
    } else if (expr instanceof Service) {
        evaluateService(parent, (Service) expr, bindings);
    } else if (expr instanceof Slice) {
        evaluateSlice(parent, (Slice) expr, bindings);
    } else if (expr instanceof Extension) {
        evaluateExtension(parent, (Extension) expr, bindings);
    } else if (expr instanceof Distinct) {
        evaluateDistinct(parent, (Distinct) expr, bindings);
    } else if (expr instanceof Reduced) {
        evaluateReduced(parent, (Reduced) expr, bindings);
    } else if (expr instanceof Group) {
        evaluateGroup(parent, (Group) expr, bindings);
    } else if (expr instanceof Order) {
        evaluateOrder(parent, (Order) expr, bindings);
    } else if (expr instanceof QueryRoot) {
        parentStrategy.sharedValueOfNow = null;
        evaluateTupleExpr(parent, ((QueryRoot) expr).getArg(), bindings);
    } else if (expr instanceof DescribeOperator) {
        evaluateDescribeOperator(parent, (DescribeOperator) expr, bindings);
    } else if (expr == null) {
        parent.handleException(new IllegalArgumentException("expr must not be null"));
    } else {
        parent.handleException(new QueryEvaluationException("Unknown unary tuple operator type: " + expr.getClass()));
    }
}
 
Example #29
Source File: PrecompJoinOptimizerTest2.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testISNUMERIC() throws Exception {

    final SPARQLParser parser1 = new SPARQLParser();
    final SPARQLParser parser2 = new SPARQLParser();

    final ParsedQuery pq1 = parser1.parseQuery(q29, null);
    final ParsedQuery pq2 = parser2.parseQuery(q30, null);

    final SimpleExternalTupleSet extTup = new SimpleExternalTupleSet(
            new Projection(pq2.getTupleExpr()));

    final List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>();
    list.add(extTup);

    final TupleExpr tup = pq1.getTupleExpr().clone();
    provider.setIndices(list);
    final PCJOptimizer pcj = new PCJOptimizer(list, false, provider);
    pcj.optimize(tup, null, null);

    final Set<StatementPattern> qSet = Sets.newHashSet(StatementPatternCollector
            .process(pq1.getTupleExpr()));
    final Set<QueryModelNode> eTupSet = PcjIntegrationTestingUtil
            .getTupleSets(tup);

    final Set<StatementPattern> set = Sets.newHashSet();
    for (final QueryModelNode s : eTupSet) {
        set.addAll(StatementPatternCollector.process(((ExternalTupleSet) s)
                .getTupleExpr()));
    }

    Assert.assertTrue(set.equals(qSet) && eTupSet.size() == 1);

}
 
Example #30
Source File: PrecompJoinOptimizerTest2.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testGeoIndexFunction() throws Exception {

    final SPARQLParser parser1 = new SPARQLParser();
    final SPARQLParser parser2 = new SPARQLParser();

    final ParsedQuery pq1 = parser1.parseQuery(q21, null);
    final ParsedQuery pq2 = parser2.parseQuery(q23, null);

    System.out.println("Query is " + pq1.getTupleExpr());
    System.out.println("Index is " + pq2.getTupleExpr());

    final SimpleExternalTupleSet extTup = new SimpleExternalTupleSet(
            new Projection(pq2.getTupleExpr()));

    final List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>();
    list.add(extTup);

    final TupleExpr tup = pq1.getTupleExpr().clone();
    provider.setIndices(list);
    final PCJOptimizer pcj = new PCJOptimizer(list, false, provider);
    pcj.optimize(tup, null, null);

    final Set<StatementPattern> qSet = Sets.newHashSet(StatementPatternCollector
            .process(pq1.getTupleExpr()));
    final Set<QueryModelNode> eTupSet = PcjIntegrationTestingUtil
            .getTupleSets(tup);

    final Set<StatementPattern> set = Sets.newHashSet();
    for (final QueryModelNode s : eTupSet) {
        set.addAll(StatementPatternCollector.process(((ExternalTupleSet) s)
                .getTupleExpr()));
    }

    Assert.assertTrue(qSet.containsAll(set) && set.size() != 0);

}