SPARQL - 查找具有最相似属性的对象

SPARQL - Find objects with the most similar properties

假设有一个人的 RDF 数据库,每个人都有许多定义此人朋友的三元组('person' x:hasFriend 'otherPerson' 中的很多)。我怎样才能找到拥有最相似朋友的人?我是 SPARQL 的新手,这似乎是一个非常复杂的查询。

基本上,结果将是一个人列表,从具有最相似朋友列表(到查询中指定的人)的人开始,然后沿着列表向下到具有最不相似朋友列表的人。

假设我在这个查询中搜索 person1,结果将类似于:

  1. person2 - 300 个相同的朋友
  2. person30 - 245 个相同的朋友
  3. person18 - 16 个相同的朋友

等等

如果您采用我对 How to find similar content using SPARQL 的回答中的方法(这可能被认为是重复的),您最终会得到如下结果:

select ?otherPerson (count(?friend) as ?numFriends) where { 
  :person1 :hasFriend ?friend .           #-- person1 has a friend, ?friend .
  ?otherPerson :hasFriend ?friend .       #-- so does ?otherPerson .
}
group by ?otherPerson       #-- One result row per ?otherPerson, 
order by desc(?numFriends)  #-- ordered by number of common friends.

如果您真的想要,可以使用反向 属性 路径使查询模式更短一些:

select ?otherPerson (count(?friend) as ?numFriends) where { 
  #-- some ?friend is a friend of both :person1 and ?otherPerson .
  ?friend ^:hasFriend :person1, ?otherPerson .
}
group by ?otherPerson       #-- One result row per ?otherPerson, 
order by desc(?numFriends)  #-- ordered by number of common friends.