How to concatenate a list of values in sparql?

前端 未结 2 1337
[愿得一人]
[愿得一人] 2021-01-05 04:22

Suppose I have a uri http://dbpedia.org/page/Manmohan_Singh now he has a list of years in his tag dbpprop:years.

When I write a query like

PREFIX r         


        
2条回答
  •  孤街浪徒
    2021-01-05 05:16

    This is similar to Aggregating results from SPARQL query, but the problem is actually a bit more complex, because there are multiple variables that have more than one result. ?name, ?office, and ?birthPlace have the same issue.

    You can work around this using group_concat, but you'll need to use distinct as well, to keep from getting, e.g., the same ?year repeated multiple times in your concatenated string. group by reduces the number of rows that you have in a solution, but in each of those rows, you have a set of values for the variables that you didn't group by. E.g., since ?year isn't in the group by, you have a set of values for ?year, and you have to do something with them. You could, e.g., select (sample(?year) as ?aYear) to grab just one from the set, or you could do as we've done here, and select (group_concat(distinct ?year;separator=", ") as ?years) to concatenate the distinct values into a string.

    You'll want a query like the following, which produces one row:

    SELECT ?x
           (group_concat(distinct ?name;separator="; ") as ?names)
           ?abs
           ?birthDate
           (group_concat(distinct ?birthplace;separator=", ") as ?birthPlaces)
           (group_concat(distinct ?year;separator=", ") as ?years)
           ?party
           (group_concat(distinct ?office;separator=", ") as ?offices)
           ?wiki
    WHERE {
      ?x owl:sameAs? dbpedia:Manmohan_Singh.
      ?x dbpprop:name ?name.
      ?x dbpedia-owl:birthDate ?birthDate.
      ?x dbpedia-owl:birthPlace ?birthplace.
      ?x dbpprop:years ?year.
      ?x dbpprop:party ?party.
      ?x dbpedia-owl:office ?office.
      ?x foaf:isPrimaryTopicOf ?wiki.
      ?x rdfs:comment ?abs.
      FILTER(langMatches(lang(?abs),"en"))
    }
    group by ?x ?abs ?birthDate ?party ?wiki
    

    SPARQL results

提交回复
热议问题