How to concatenate a list of values in sparql?

こ雲淡風輕ζ 提交于 2019-11-30 20:11:03
Joshua Taylor

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

Look at GROUP_CONCAT but it may be easier to retrieve the data in multiple rows (you can sort to put repeats adjacent to each other) and process in code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!