Java Code Examples for org.eclipse.rdf4j.query.TupleQuery#setIncludeInferred()

The following examples show how to use org.eclipse.rdf4j.query.TupleQuery#setIncludeInferred() . 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: SPARQLQueryBuilder.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public List<KBHandle> asHandles(RepositoryConnection aConnection, boolean aAll)
{
    long startTime = currentTimeMillis();
    String queryId = toHexString(hashCode());

    String queryString = selectQuery().getQueryString();
    //queryString = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, queryString, null)
    //        .toString();
    LOG.trace("[{}] Query: {}", queryId, queryString);

    List<KBHandle> results;
    if (returnEmptyResult) {
        results = emptyList();
        
        LOG.debug("[{}] Query was skipped because it would not return any results anyway",
                queryId);
    }
    else {
        TupleQuery tupleQuery = aConnection.prepareTupleQuery(queryString);
        tupleQuery.setIncludeInferred(includeInferred);
        results = evaluateListQuery(tupleQuery, aAll);
        results.sort(Comparator.comparing(KBObject::getUiLabel, String.CASE_INSENSITIVE_ORDER));
        
        LOG.debug("[{}] Query returned {} results in {}ms", queryId, results.size(),
                currentTimeMillis() - startTime);
    }

    return results;
}
 
Example 2
Source File: SPARQLQueryBuilder.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<KBHandle> asHandle(RepositoryConnection aConnection, boolean aAll)
{
    long startTime = currentTimeMillis();
    String queryId = toHexString(hashCode());

    limit(1);
    
    String queryString = selectQuery().getQueryString();
    LOG.trace("[{}] Query: {}", queryId, queryString);

    Optional<KBHandle> result;
    if (returnEmptyResult) {
        result = Optional.empty();
        
        LOG.debug("[{}] Query was skipped because it would not return any results anyway",
                queryId);
    }
    else {
        TupleQuery tupleQuery = aConnection.prepareTupleQuery(queryString);
        tupleQuery.setIncludeInferred(includeInferred);
        result = evaluateListQuery(tupleQuery, aAll).stream().findFirst();
        
        LOG.debug("[{}] Query returned a result in {}ms", queryId,
                currentTimeMillis() - startTime);
    }

    return result;
}
 
Example 3
Source File: NoReification.java    From inception with Apache License 2.0 5 votes vote down vote up
private List<Statement> listStatements(TupleQuery aQuery, boolean aIncludeInferred)
{
    aQuery.setIncludeInferred(aIncludeInferred);
    
    try (TupleQueryResult result = aQuery.evaluate()) {
        ValueFactory vf = SimpleValueFactory.getInstance();
        
        List<Statement> statements = new ArrayList<>();
        while (result.hasNext()) {
            BindingSet bindings = result.next();
            if (bindings.size() == 0) {
                continue;
            }
            
            // LOG.trace("[{}] Bindings: {}", toHexString(hashCode()), bindings);
            
            Binding subj = bindings.getBinding(VAR_SUBJECT_NAME);
            Binding pred = bindings.getBinding(VAR_PREDICATE_NAME);
            Binding obj = bindings.getBinding(VAR_OBJECT_NAME);

            IRI subject = vf.createIRI(subj.getValue().stringValue());
            IRI predicate = vf.createIRI(pred.getValue().stringValue());
            Statement stmt = vf.createStatement(subject, predicate, obj.getValue());
            
            // Avoid duplicate statements
            if (!statements.contains(stmt)) {
                statements.add(stmt);
            }
        }
        return statements;
    }
}
 
Example 4
Source File: WikiDataReification.java    From inception with Apache License 2.0 5 votes vote down vote up
private List<Statement> getQualifiersById(RepositoryConnection aConnection, KnowledgeBase kb,
        String aStatementId)
{
    ValueFactory vf = aConnection.getValueFactory();
    
    String QUERY = String.join("\n",
            "SELECT DISTINCT ?p ?o WHERE {",
            "  ?id ?p ?o .",
            "}",
            "LIMIT " + kb.getMaxResults());
    Resource id = vf.createBNode(aStatementId);
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("id", id);

    tupleQuery.setIncludeInferred(false);
    TupleQueryResult result;

    try {
        result = tupleQuery.evaluate();
    }
    catch (QueryEvaluationException e) {
        log.warn("No such statementId in knowledge base", e);
        return null;
    }

    List<Statement> statements = new ArrayList<>();
    while (result.hasNext()) {
        BindingSet bindings = result.next();
        Binding p = bindings.getBinding("p");
        Binding o = bindings.getBinding("o");

        if (!p.getValue().stringValue().contains(PREDICATE_NAMESPACE)) {
            IRI predicate = vf.createIRI(p.getValue().stringValue());
            Value object = o.getValue();
            Statement qualifierStatement = vf.createStatement(id, predicate, object);
            statements.add(qualifierStatement);
        }
    }
    return statements;
}
 
Example 5
Source File: TupleQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testStreaming() throws Exception {
	ValueFactory vf = con.getValueFactory();
	int subjectIndex = 0;
	int predicateIndex = 100;
	int objectIndex = 1000;
	int testStatementCount = 1000;
	int count = 0;
	con.begin();
	while (count < testStatementCount) {
		con.add(vf.createIRI("urn:test:" + subjectIndex), vf.createIRI("urn:test:" + predicateIndex),
				vf.createIRI("urn:test:" + objectIndex));
		if (Math.round(Math.random()) > 0) {
			subjectIndex++;
		}
		if (Math.round(Math.random()) > 0) {
			predicateIndex++;
		}
		if (Math.round(Math.random()) > 0) {
			objectIndex++;
		}
		count++;
	}
	con.commit();

	for (int evaluateCount = 0; evaluateCount < 1000; evaluateCount++) {
		try (ByteArrayOutputStream stream = new ByteArrayOutputStream();
				RepositoryConnection nextCon = rep.getConnection();) {
			TupleQueryResultWriter sparqlWriter = QueryResultIO.createTupleWriter(TupleQueryResultFormat.SPARQL,
					stream);
			TupleQuery tupleQuery = nextCon.prepareTupleQuery(QueryLanguage.SPARQL,
					"SELECT ?s ?p ?o WHERE { ?s ?p ?o . }");
			tupleQuery.setIncludeInferred(false);
			tupleQuery.evaluate(sparqlWriter);
		}
	}
}
 
Example 6
Source File: SPARQLConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private RepositoryResult<Statement> getStatementsQuadMode(Resource subj, IRI pred, Value obj,
		boolean includeInferred, Resource... contexts)
		throws MalformedQueryException, RepositoryException, QueryEvaluationException {
	TupleQueryResult qRes = null;
	RepositoryResult<Statement> result = null;

	boolean allGood = false;
	try {
		TupleQuery tupleQuery = prepareTupleQuery(SPARQL, EVERYTHING_WITH_GRAPH);
		setBindings(tupleQuery, subj, pred, obj, contexts);
		tupleQuery.setIncludeInferred(includeInferred);
		qRes = tupleQuery.evaluate();
		result = new RepositoryResult<>(new ExceptionConvertingIteration<Statement, RepositoryException>(
				toStatementIteration(qRes, subj, pred, obj)) {

			@Override
			protected RepositoryException convert(Exception e) {
				return new RepositoryException(e);
			}
		});
		allGood = true;
		return result;
	} finally {
		if (!allGood) {
			try {
				if (result != null) {
					result.close();
				}
			} finally {
				if (qRes != null) {
					qRes.close();
				}
			}
		}
	}
}
 
Example 7
Source File: WikiDataReification.java    From inception with Apache License 2.0 4 votes vote down vote up
private List<Statement> getStatementsById(RepositoryConnection aConnection, KnowledgeBase kb,
        String aStatementId)
{
    ValueFactory vf = aConnection.getValueFactory();
    
    String QUERY = String
        .join("\n",
            "SELECT DISTINCT ?s ?p ?ps ?o WHERE {",
            "  ?s  ?p  ?id .",
            "  ?id ?ps ?o .",
            "  FILTER(STRSTARTS(STR(?ps), STR(?ps_ns)))",
            "}",
            "LIMIT 10");
    Resource id = vf.createBNode(aStatementId);
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("id", id);
    tupleQuery.setBinding("ps_ns", vf.createIRI(PREDICATE_NAMESPACE));

    tupleQuery.setIncludeInferred(false);
    TupleQueryResult result;

    try {
        result = tupleQuery.evaluate();
    }
    catch (QueryEvaluationException e) {
        log.warn("No such statementId in knowledge base", e);
        return null;
    }

    List<Statement> statements = new ArrayList<>();
    while (result.hasNext()) {
        BindingSet bindings = result.next();
        Binding s = bindings.getBinding("s");
        Binding p = bindings.getBinding("p");
        Binding o = bindings.getBinding("o");
        Binding ps = bindings.getBinding("ps");

        IRI instance = vf.createIRI(s.getValue().stringValue());
        IRI predicate = vf.createIRI(p.getValue().stringValue());
        Statement root = vf.createStatement(instance, predicate, id);

        IRI valuePredicate = vf.createIRI(ps.getValue().stringValue());
        Value object = o.getValue();
        Statement valueStatement = vf.createStatement(id, valuePredicate, object);
        statements.add(root);
        statements.add(valueStatement);
    }
    return statements;
}
 
Example 8
Source File: SailConnectionQueryPreparer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public TupleQuery prepare(ParsedTupleQuery tupleQuery) {
	TupleQuery query = new SailConnectionTupleQuery(tupleQuery, con);
	query.setIncludeInferred(includeInferred);
	return query;
}
 
Example 9
Source File: SailQueryPreparer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public TupleQuery prepare(ParsedTupleQuery tupleQuery) {
	TupleQuery query = new SailTupleQuery(tupleQuery, con);
	query.setIncludeInferred(includeInferred);
	return query;
}