Search code examples
sparqlrdf4j

Constructing a sparql query using rdf4j


I'm trying to construct a SPARQL query using the rdf4j documentation: https://rdf4j.org/documentation/tutorials/sparqlbuilder/

I am a newbie to java (and stackoverflow, apologies if this is poorly written), but I think I have included the right beginning steps. I have instantiated a select query, a prefix and a variable in the following way:

    SelectQuery draftQuery = Queries.SELECT();

    Prefix default = SparqlBuilder.prefix("dc", Rdf.iri("url"));

    Variable draftCount = SparqlBuilder.var("draftCount");

url has been substituted with the right prefix

The query I am trying to write is: SELECT ?x WHERE { :team_1 :draftCount ?x}, but ?x has no rdf:type and is simply a value that is attached to :draftCount. I have no idea how to write it as a SPARQL query within java, because from what I understand within the docs, the example included where the product is a book, the product has rdf:type "book". I don't want to query multiple variables (e.g. :team_1 ?x ?y) because there are other triples attached to the team and I want to query them separately. I want to have another SPARQL query later that is similar but is SELECT ?x WHERE { :team_1 :completedCount ?x},

How can I write this query? This is what I have so far:

    draftQuery.prefix(default).select(draftCount)

Solution

  • You made a good start, but you are mixing up variables and IRIs: :team_1 and :draftCount are IRIs in your query, not variables. Only ?x is a variable. Since you are using the default namespace for your IRs, just create a Prefix object for the default namespace, like so:

    Prefix defaultNs = SparqlBuilder.prefix(Rdf.iri("http://example.org/"));
    

    and then you can use that to create Iri objects for use in the query, like so:

    Iri team1 = defaultNs.iri("team_1");
    

    To add a relation other than rdf:type using the SparqlBuilder, use the .has method.

    Putting it all together, to produce this SPARQL query string:

    PREFIX: <http://example.org/>
    SELECT ?x WHERE { :team_1 :draftCount ?x}
    

    You do this:

    Prefix defaultNs = SparqlBuilder.prefix(Rdf.iri("http://example.org/"));
    Iri team_1 = defaultNs.iri("team_1"), draftCount = defaultNs.iri("draftCount");
    Variable x = SparqlBuilder.var("x");
            
    SelectQuery query = Queries.SELECT()
                .prefix(defaultNs)
                .select(x)
                .where(team_1.has(draftCount, x));
    
    System.out.println(query.getQueryString());