query with FILTER(?document = “uriNode”) returns n

2020-05-07 02:01发布

问题:

I am executing the SPARQL query below with Jena, where uriNode is a String representing a URI, but this query doesn't give me any results. I've already checked the database and this URI does exist there. What's the problem?

String queryString2 = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                    "PREFIX dc: <http://purl.org/dc/elements/1.1/> SELECT ?author WHERE { " +
                    "?document dc:creator ?author." +
                    "FILTER (?document = \"" + uriNode + "\" ). }";

回答1:

AndyS's answer is right, insofar as that you're currently checking whether ?document is some particular string. Since strings (and more generally, literals) can't be the subject of triples in RDF, you'll never get any solutions this way. You actually need to check whether it's a particular URI. You could do that with a filter like this

FILTER( ?document = <http://example.org/node> )

but that's really very wasteful, because a query like the following (based on yours) is retrieving all the things with dc:creators and then throwing most of them out.

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?author WHERE {
  ?document dc:creator ?author.
  FILTER (?document = <http://example.org/node> ).
}

It's literally like asking a library catalog for a list of all the books and their authors, and then going through them one by one and discarding the results for all but one book. A much more efficient solution would be to ask for the dc:creator of the thing that you actually care about, because this will only select the data that you want, and it won't have to do any filtering:

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?author WHERE {
  <http://example.org/node> dc:creator ?author.
}

You can do a similar thing if you needed, e.g., to select documents with a specific title; use a query like this:

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?document WHERE {
  ?document dc:title "Reply to Hayne" .
  # or, if language tags are in use, 
  # ?document dc:title "Reply to Hayne"@en
}


回答2:

You are testing whether ?document is the string ?uriNode, not testing as a URI.

FILTER (?document = <" + uriNode + ">" )


标签: rdf sparql jena