首页 > 解决方案 > 获取 Wikidata 项的所有子项(但不是实例)

问题描述

例如,采取这三种情况:

Triangle Shirtwaist Factory fire (Q867316) : instance of (P31): disaster (Q3839081)
disaster:  subclass of (P279) :  occurrence (Q1190554) 
occurrence (Q1190554) : subclass of:  temporal entity (Q26907166) 

World's Fair (Q172754) : subclass of (P279) :  exhibition (Q464980) 
exhibition (Q464980)  : subclass of (P279) :  event (Q1656682) 
event (Q1656682) : subclass of (P279) : occurrence (Q1190554)
occurrence (Q1190554) : subclass of:  temporal entity (Q26907166) 

Peloponnesian War (Q33745) :  instance of (P31):  war (Q198) 
war (Q198) : subclass of (P279) : occurrence (Q1190554)
occurrence (Q1190554) : subclass of:  temporal entity (Q26907166)

我希望所有的后代都在实例( , , )temporal entity之前停止。Triangle Shirtwaist Factory fireWorld's FairPeloponnesian War

有没有办法用 SPARQL 或 API 做到这一点?

标签: sparqlwikidatawikidata-api

解决方案


如果我理解正确,您只想了解实例在 Wikidata 上的分类方式。

所以从@AKSW给出的例子开始:

SELECT DISTINCT ?event_type ?event_typeLabel { 
    ?event_type wdt:P279* wd:Q26907166 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 100

*是一项非常昂贵的计算操作,在撰写本文时,Wikidata 已接近 5000 万个项目。这就是为什么我必须添加的原因,LIMIT因为没有它我会超时。

绘制它

为了感受数据,我喜欢在 Wikidata 图形构建器中查看它。因为它显示聚类非常好。

https://angryloki.github.io/wikidata-graph-builder/?property=P279&item=Q26907166&iterations=2&mode=reverse

在此处输入图像描述

如您所见,在 2 次迭代后已经有很多分类。所以我们可能也已经对这个查询感到满意了:

SELECT DISTINCT ?event_type ?event_typeLabel { 
    ?event_type wdt:P279/wdt:P279 wd:Q26907166 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

请注意,它仅沿属性 P279 运行 2 次。目前这给了我 281 项。

如果您真的需要完全遍历树,您可以使用FILTER NOT EXISTS. 但问题是目前总是遇到超时:

SELECT DISTINCT ?event_type ?event_typeLabel { 
    ?event_type wdt:P279* wd:Q26907166 .
    FILTER NOT EXISTS { ?event_type wdt:P31 [] }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 100

使用子查询,您可以限制树中的结果,但您将获得不完整的数据:

SELECT ?event_type ?event_typeLabel
WHERE
{
    {
      SELECT DISTINCT ?event_type
      WHERE                
      { 
        ?event_type wdt:P279* wd:Q26907166 .
      }
      LIMIT 1000
    }

    SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } 
    FILTER NOT EXISTS { ?event_type wdt:P31 [] }   
}

推荐阅读