3

Lets say there is a RDF DB of people and each of these people has many triples defining this person's friends (so many of 'person' x:hasFriend 'otherPerson'). How can I find people who have the most similar friends? I'm a novice at SPARQL and this seems like a really complex query.

Basically, the results would be a list of people starting from the ones with the most similar friends list (to the person specified in the query) and then going down the list to the people with the least similar friends list.

So lets say I search this query for person1, the results would be something like:

  1. person2 - 300 of the same friends
  2. person30 - 245 of the same friends
  3. person18 - 16 of the same friends

etc.

TallTed
  • 9,069
  • 2
  • 22
  • 37
Fabis
  • 1,932
  • 2
  • 20
  • 37
  • I think that the answer to [How to find similar content using SPARQL](http://stackoverflow.com/questions/21290186/how-to-find-similar-content-using-sparql) might provide an answer to this. The last SPARQL query in the answer "[uses] the number of common properties as a measure of similarity." – Joshua Taylor Apr 27 '16 at 11:32

1 Answers1

4

If you adapt the approach in my answer to How to find similar content using SPARQL (of which this might be considered a duplicate), you'd end up with something like:

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.

If you really want to, you can use a reverse property path to make the query pattern a little shorter:

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.
Community
  • 1
  • 1
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
  • Man thanks a lot. Yeah, I tried Googling for help, but I couldn't find anything because I didn't know what exactly to ask. – Fabis Apr 27 '16 at 12:20
  • @Fabis Yeah, some of these things aren't always super hard, but if there's no single term to describe them, they can be really hard to search for. – Joshua Taylor Apr 27 '16 at 12:21