jimmy
jimmy

Reputation: 1413

Aggregating and ordering over relationship properties

I'm a Cypher newbie so I might be missing something obvious but after reading all the basic recommendation engine posts/tutorials I could find, I can't seem to be able to solve this so all help is appreciated.

I'm trying to make a recommendation function that recommends Places to User based on Tags from previous Places she enjoyed. User have LIKES relationship to Tag which carries weight property. Places have CONTAINS relationship with Tag but Contain doesn't have any weights associated with it. Also the more Tags with LIKES weighted above certain threshold (0.85) Place has, the higher it should be ordered so this would add SUM aggregator.

(User)-[:LIKES]->(Tag)<-[:CONTAINS]-(Place)

My problem is that I can't wrap my head around how to order Places based on the amount of Tags pointing to it that have LIKES relationship with User and then how to use LIKES weights to order Places.

Upvotes: 1

Views: 40

Answers (1)

Christophe Willemsen
Christophe Willemsen

Reputation: 20185

Based on the following example neo4j console : http://console.neo4j.org/r/klmu5l

The following query should do the trick :

MATCH (n:User {login:'freeman.williamson'})-[r:LIKES]->(tag)
MATCH (place:Place)-[:CONTAINS]->(tag)
WITH place, sum(r.weight) as weight, collect(tag.name) as tags
RETURN place, size(tags) as rate, weight
ORDER BY rate DESC, weight DESC

Which returns :

(42:Place {name:"Alveraville"}) 6   491767416
(38:Place {name:"Raynorshire"}) 5   491766715
(45:Place {name:"North Kristoffer"})    5   491766069
(36:Place {name:"Orrinmouth"})  5   491736638
(44:Place {name:"New Corachester"}) 5   491736001

Explanation :

  • I match the user and the tags he likes
  • I match the places containing at least one tag he likes
  • Then I use WITH to pipe the sum of the rels weights, a collection of the tags, and the place
  • Then I return those except I count with size the number of tags in the collection
  • All ordered in descending order

Upvotes: 3

Related Questions