Skip to content

Instantly share code, notes, and snippets.

@paulozullu
Last active February 26, 2016 18:01
Show Gist options
  • Save paulozullu/4b34691bda9674423f24 to your computer and use it in GitHub Desktop.
Save paulozullu/4b34691bda9674423f24 to your computer and use it in GitHub Desktop.
With pyneo, get users whose first category of preference is sports, live in São Paulo and are males between 18 and 32 years old​
#-*- coding: utf-8 -*-
'''
Created on 25 de fev de 2016
'''
from py2neo import Graph, authenticate
import datetime
from dateutil.relativedelta import relativedelta
now = datetime.datetime.now()
authenticate("localhost:7474", "", "")
graph = Graph()
query = "MATCH (all:User) WITH count(all) AS total "
query += "MATCH (g:Gender {name:'m'})<-[:GENDER_IS]-(user:User)-[:CITY_OF_RESIDENCE]->(c:City {name:'São Paulo'}) "
query += "MATCH (user)-[:FIRST_CATEGORY_OF_INTEREST]->(category:Category {name:'sports'}) "
query += "RETURN user, category, total"
result = graph.cypher.execute(query)
users = []
for item in result:
dob = datetime.datetime.strptime(str(item["user"]["dob"]), '%d/%m/%Y')
difference_in_years = relativedelta(now, dob).years
if difference_in_years >= 18 and difference_in_years <= 32:
data = {}
data["username"] = item["user"]["username"]
data["category"] = item["category"]["name"]
data["age"] = str(difference_in_years)
users.append(data)
for user in users:
print user["username"] + " has " + user["age"] + " years, is male and his first category of choice is " + user["category"] + "."
if len(users) <= 0:
print "\nMatching query has no results"
elif len(users) == 1:
print "\nThere is one user from a total of %d representing %f%s of the users" %(result[0]["total"], 1 / float(result[0]["total"]) * 100, "%")
else:
print "\nThere are %d users from a total of %d representing %f%s of the users" %(len(users), result[0]["total"], float(len(users)) / float(result[0]["total"]) * 100, "%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment