【问题标题】:Combine results of 2 Queries合并 2 个查询的结果
【发布时间】:2017-01-24 12:00:28
【问题描述】:

我有一个 python 脚本,它使用 2 个 SPARQL 查询来查询 DBpedia,并且对于每个查询,将结果放在一个列表中。然后我制作了一组这个列表来删除重复项,我得到了我需要的结果。如果有可能组合查询以加快此过程,这似乎是一种低效的方法。

SQL SPARQL 方面有经验的人可以帮我结合这些查询来加快我的 python 脚本吗?

对于上下文:我想要我给这个函数(查询 1)的查询词的 DBpedia 页面的所有属性的属性和值的标签名称,以及那些具有数字/文本值而不是标签的标签名称作为值(查询 2)。

def querydbpedia(queryword):
mylist = list()
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
  prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> 

  SELECT DISTINCT ?pLabel ?oLabel ?o WHERE {
     <http://dbpedia.org/resource/""" + queryword + """> ?p ?o.
     ?p rdfs:label ?pLabel .
     ?o rdfs:label ?oLabel .
     FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en"))
     FILTER(LANG(?oLabel) = "" || LANGMATCHES(LANG(?oLabel), "en"))
  }
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
  mystr = (result["pLabel"]["value"] + " - " + result["oLabel"]["value"]).lower()
  mylist.append(mystr)

sparql.setQuery("""
  prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> 

  SELECT DISTINCT ?pLabel ?oLabel ?o WHERE {
     <http://dbpedia.org/resource/""" + queryword + """> ?p ?o.
     ?p rdfs:label ?pLabel .
     OPTIONAL {?o rdfs:label ?oLabel} .
     FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en"))
     FILTER(LANG(?o) = "" || LANGMATCHES(LANG(?o), "en"))
  }
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
  mystr = (result["pLabel"]["value"] + " - " + result["o"]["value"]).lower()
  if not ("abstract" in mystr):
     mylist.append(mystr)

mylist = list(set(mylist))
return mylist

【问题讨论】:

    标签: python sparql semantic-web dbpedia


    【解决方案1】:

    您可以使用 SPARQL UNION

    或者您可以使用 SPARQL 1.1 VALUES,将相同的查询应用于多个资源。例如——

      PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> 
      SELECT DISTINCT ?s ?pLabel ?oLabel ?o WHERE {
         ?s ?p ?o.
         VALUES ?s {<http://dbpedia.org/resource/Leipzig> <http://dbpedia.org/resource/Dresden>}
         ?p rdfs:label ?pLabel .
         ?o rdfs:label ?oLabel .
         FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en"))
         FILTER(LANG(?oLabel) = "" || LANGMATCHES(LANG(?oLabel), "en"))
      }
    

    【讨论】:

    • 我很确定 UNION 是我正在寻找的东西,但我尝试自己做这件事,但我似乎无法做到正确。如果我对这些查询进行 UNION,我似乎无法获得与原始 2 个查询相同的结果。我应该如何对这些查询执行 UNION?
    • 为什么不能使用 VALUES 代替?这样方便多了。不行吗?
    • 您能显示您尝试过的 UNION 查询吗?什么不适合它?注意,在这种情况下你必须保留主题的变量,否则你无法区分这两种资源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多