Skip to content

Instantly share code, notes, and snippets.

@jeanmidevacc
Created May 12, 2020 01:52
Show Gist options
  • Save jeanmidevacc/b64633246236bebe789b522f599dbc9b to your computer and use it in GitHub Desktop.
Save jeanmidevacc/b64633246236bebe789b522f599dbc9b to your computer and use it in GitHub Desktop.
neo4j_recommender_jaccard.py
%%time
def get_recommendations_jaccard(user_id):
# Based on the code in https://neo4j.com/docs/graph-data-science/current/alpha-algorithms/jaccard/
query = f"""
MATCH (u1:User)-[:BOOKMARKED]->(song1)
WITH u1, collect(id(song1)) AS u1Song
WHERE u1.id = '{user_id}'
MATCH (u2:User)-[:BOOKMARKED]->(song2) WHERE u1 <> u2
WITH u1, u1Song, u2, collect(id(song2)) AS u2Song
RETURN u2.id AS user_id,
gds.alpha.similarity.jaccard(u1Song, u2Song) AS similarity
ORDER BY user_id, similarity DESC
"""
with driver.session() as session:
result = session.run(query)
df_recommendations = pd.DataFrame([r for r in result.values()])
df_recommendations.columns = ['user_id', 'similarity']
df_recommendations = df_recommendations[df_recommendations['similarity'] > 0]
df_recommendations.sort_values(['similarity'], ascending = False, inplace = True)
return df_recommendations['user_id'].tolist()
recommendations = get_recommendations_jaccard('jeanmidev')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment