【问题标题】:how to remove duplicates in sparql query如何在 sparql 查询中删除重复项
【发布时间】:2016-07-20 18:54:41
【问题描述】:

我写了这个查询并返回夫妇和特定条件的列表。 (在http://live.dbpedia.org/sparql)

SELECT DISTINCT ?actor ?person2 ?cnt
WHERE
{
{
    select DISTINCT ?actor ?person2 (count (?film) as ?cnt) 
    where { 
        ?film    dbo:starring ?actor .
        ?actor dbo:spouse ?person2. 
        ?film    dbo:starring ?person2.
    }
    order by ?actor
}
FILTER (?cnt >9)
}

问题是某些行是重复的。 示例:

http://dbpedia.org/resource/George_Burnshttp://dbpedia.org/resource/Gracie_Allen12

http://dbpedia.org/resource/Gracie_Allenhttp://dbpedia.org/resource/George_Burns12

如何删除这些重复? 我在 ?actor 中添加了性别,但它会损坏当前结果。

【问题讨论】:

    标签: sparql dbpedia


    【解决方案1】:

    Natan Cox's answer 展示了排除此类伪重复的典型方法。结果实际上并不重复,因为在一个中,例如,George Burns 是?actor,而在另一个中,他是?person2。在许多情况下,您可以添加一个过滤器来要求这两件事是有序的,这将删除重复的案例。例如,当您有如下数据时:

    :a :likes :b .
    :a :likes :c .
    

    然后你搜索

    select ?x ?y where { 
      :a :likes ?x, ?y .
    }
    

    您可以添加 filter(?x 来强制在 ?x 和 ?y 之间进行排序,这将删除这些伪重复。然而,在这种情况下,它有点棘手,因为没有找到 ?actor 和 ?person2 使用相同的标准。如果 DBpedia 包含

    :PersonB dbo:spouse :PersonA
    

    但不是

    :PersonA dbo:spouse :PersonB
    

    那么简单的过滤器将不起作用,因为您永远不会找到主体 PersonA 小于对象 PersonB 的三元组。因此,在这种情况下,您还需要稍微修改查询以使条件对称:

    select distinct ?actor ?spouse (count(?film) as ?count) {
      ?film dbo:starring ?actor, ?spouse .
      ?actor dbo:spouse|^dbo:spouse ?spouse .
      filter(?actor < ?spouse)
    }
    group by ?actor ?spouse
    having (count(?film) > 9)
    order by ?actor
    

    (这个查询也表明你在这里不需要子查询,你可以使用 having 来“过滤”聚合值。)但重要的部分是使用属性路径 dbo:spouse|^dbo:spouse 找到 ?spouse 的值,使得 either ?actor dbo:spouse ?spouse ?spouse dbo:spouse ?actor。这使得关系对称,因此即使关系仅在一个方向上声明,也可以保证获得所有对。

    【讨论】:

    • 不错。您甚至可以将解决方案推广到任何反向属性关系。
    【解决方案2】:

    这当然不是实际的重复,因为您可以从两个方面查看它。如果您愿意,修复它的方法是添加一个过滤器。这有点脏,但它只占用“相同”的 2 行。

    SELECT DISTINCT ?actor ?person2 ?cnt
    WHERE
    {
    {
        select DISTINCT ?actor ?person2 (count (?film) as ?cnt) 
        where { 
            ?film    dbo:starring ?actor .
            ?actor dbo:spouse ?person2. 
            ?film    dbo:starring ?person2.
    FILTER (?actor < ?person2)
    
    
        }
        order by ?actor
    }
    FILTER (?cnt >9)
    }
    

    【讨论】:

    • 我也想到了这一点,但这还不够,因为这可能是三元组并非都存在于两个方向上。这可能会错过解决方案。
    • 好的。真的。这仅在您假设完整的数据或推理时才有效。
    • 我添加了 an answer,它展示了如何在不进行推理的情况下执行此操作(并且还以不需要子查询的方式)。
    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2019-12-11
    相关资源
    最近更新 更多