0

I'm looking for the way how to get all statements from my model by its property and by a class of an object.

For example I have property :driverOf and individuals either of type Bus or Truck. Then I want to get all statements where the property is :driverOf and the object is instanceOf Bus. Thanks.

UPDATE 1

Actually I need the result to be a set of statements (resp. StmtIterator) because in my app I use statement objects already. I think the most clean solution would be to have subproperties of :driverOf property, something like :driverOfBus and :driverOfTruck. But it would make my app more complicated, so I would like to find out some simple workaround.

user3024710
  • 515
  • 1
  • 6
  • 15

2 Answers2

1

You could use sparql query. You have to replace labels with full namespaces.

String queryString =
    "SELECT ?x WHERE { ?x driverOflabel ?y . {?y a Buslabel} UNION { ?y a Trucklabel} . }";

Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, YOURMODEL);
try {
    ResultSet results = qexec.execSelect();
    while(results.hasNext()) {
        QuerySolution soln = results.nextSolution();
        System.out.println(soln.toString());
    }
} finally {
    qexec.close();
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
dziewxc
  • 101
  • 1
  • 5
  • Many thanks for your reply! However I need the result to be statements... Please see my update. – user3024710 Sep 21 '15 at 07:35
  • You could create statements from results that QuerySolution gives you. `Statement stmt = ResourceFactory.createStatement(soln.getResource("x"), yourresource, soln.getResource("y"));` – dziewxc Sep 21 '15 at 13:23
1

I hope i understood this correctly:

Say you have model m and namespace NAMESPACE

// Get the property and the subject
Property driverOf = m.getProperty(NAMESPACE + "driverOf");
Resource bus = m.getResource(NAMESPACE + "bus");

// Get all statements/triples of the form (****, driverOf, bus)
StmtIterator stmtIterator = m.listStatements(null, driverOf, bus);
while (stmtIterator.hasNext()){
    Statement s = stmtIterator.nextStatement();
    Resource busDriver = s.getObject();
    // do something to the busdriver (only nice things, everybody likes busdrivers)
}
Laurens Koppenol
  • 2,946
  • 2
  • 20
  • 33