Ruby SPARQL Client是否支持Label SERVICE?如何替换FILTER实现?
Ruby SPARQL Client对Wikibase Label SERVICE的支持及代码修改
支持性说明
Ruby SPARQL Client完全支持Wikibase的Label SERVICE语法,你可以通过客户端的DSL方法或者直接编写原生SPARQL字符串两种方式实现。
代码修改方案
方案1:使用客户端DSL的service方法
通过DSL的service方法构建Label SERVICE子句,替换原有的filter语句:
client = SPARQL::Client.new("query.wikidata.org/bigdata/namespace/wdq/sparql") wd = RDF::Vocabulary.new("http://www.wikidata.org/entity/") schema = RDF::Vocabulary.new("http://schema.org/") # 补充原代码缺失的schema词汇表定义 rdf_object = RDF::Literal.new(params[:orcid]) # 定义Wikibase和bd的词汇表 wikibase = RDF::Vocabulary.new("http://wikiba.se/ontology#") bd = RDF::Vocabulary.new("http://www.bigdata.com/rdf#") query = client.select .where([:item, RDF::RDFS.label, :itemLabel], [wd[rdf_object], RDF::RDFS.label, :itemLabel], [wd[rdf_object], schema.description, :schema]) .service(wikibase[:label]) do |s| s.where([bd[:serviceParam], wikibase[:language], "en"]) end
方案2:直接嵌入原生SPARQL字符串
如果更习惯原生SPARQL语法,可直接拼接包含SERVICE的查询语句:
client = SPARQL::Client.new("query.wikidata.org/bigdata/namespace/wdq/sparql") wd = RDF::Vocabulary.new("http://www.wikidata.org/entity/") schema = RDF::Vocabulary.new("http://schema.org/") rdf_object = RDF::Literal.new(params[:orcid]) sparql_query = <<~SPARQL SELECT ?item ?itemLabel ?schema WHERE { ?item rdfs:label ?itemLabel. #{wd[rdf_object].to_s} rdfs:label ?itemLabel. #{wd[rdf_object].to_s} schema:description ?schema. SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } } SPARQL query = client.query(sparql_query)
注意事项
- 原代码中未定义
schema词汇表,必须补充定义才能正常使用schema.description,否则会出现未定义常量的错误。 - 使用DSL方式时,提前定义
wikibase和bd词汇表可以保持代码的类型安全,避免直接拼接字符串的潜在问题。
内容的提问来源于stack exchange,提问作者s0rin
相关产品推荐
相关产品推荐

