SPARQL query with FILTER returning correct values for its variables BUT only the given value for the variable being filtered

StackOverflow https://stackoverflow.com/questions/20453478

  •  30-08-2022
  •  | 
  •  

Pergunta

I'm using Jena to make a SPARQL query to search for all a document's properties by its subject. But the documents can have more than one subject, and when I do the search, it doesn't return me all the documents' properties, including all the documents' subjects, but even if it has 3 subjects (for example) it returns me all the documents properties + only the subject I set at FILTER.

I'd like to have as a return all the properties from the found document + all the subjects (that belong to the found document) and not only the one at FILTER.

Query (this.subject is a variable that has its value set in a JSF page):

String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "PREFIX dc: <http://purl.org/dc/elements/1.1/> " +
                "PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?document ?subject" +
                " ?title ?description ?language WHERE { " +
                "?document dc:title ?title." +
                "?document dc:subject ?subject." +
                "?document dc:description ?description." +
                "?document dc:language ?language." +
                "FILTER ( regex(?subject, replace( \"" + this.subject + "\", ' ', '|' ), 'i' )). }";

Thank you!

Foi útil?

Solução

You likely want to use a sub-query to restrict to the documents matching the FILTER and then select the rest of the stuff you are actually interesting in e.g.

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dc : <http://purl.org/dc/elements/1.1/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?document ?subject ?title ?description ?language
WHERE
{
  { 
    SELECT ?document
    WHERE 
    {
      ?document dc:subject ?subject . 
      FILTER(REGEX(?subject, REPLACE("search term", " ", "|"), "i"))
    }
  }
  ?document dc:title ?title ;
            dc:description ?description ;
            dc:subject ?subject ;
            dc:language ?language .
}

Note that this is still going to give you a row for each document-subject combination so if you have a document with 3 subjects you'll get three rows for that document. If you want to combine documents into a single row then you can use GROUP BY and then a GROUP_CONCAT aggregate, there are other questions already on Stack Overflow that detail how to do that.

Notes

Also note that using simple string concatenation to inject constants into your query is ill advised, take a look at Jena's ParameterizedSparqlString for a more user friendly and SPARQL injection proof API for building queries.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top