from psycopg2 import connect import random import time import sys CREA

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from psycopg2 import connect
import random
import time
import sys
"""
CREATE TABLE user_friend
(
u_id integer NOT NULL,
f_id integer NOT NULL
);
CREATE INDEX i
ON user_friend
USING btree
(u_id);
CREATE TABLE user_tags
(
u_id integer NOT NULL,
tag_id integer NOT NULL
);
CREATE INDEX i2
ON user_tags
USING btree
(u_id);
"""
conn = connect('dbname=test')
cur = conn.cursor()
u_ids = range(1e+6)
t_ids = range(1000)
if '--generate' in sys.argv:
for i in xrange(1000):
friend_ids = random.sample(u_ids, int(random.normalvariate(1000,200)))
print("making friends for %d" % i)
cur.executemany('insert into user_friend values(%s, %%s)' % i, zip(friend_ids))
conn.commit()
def test(u_id):
# give untagged users some tags
cur.execute('select f_id from user_friend where u_id = %d and f_id not in (select u_id from user_tags)'%u_id)
friend_ids = cur.fetchall()
print("need tags for %d friends" % len(friend_ids))
for f_id, in friend_ids:
tags_ids = random.sample(t_ids, max(3,int(random.normalvariate(15, 5))))
cur.executemany('insert into user_tags values(%d, %%s)'%f_id, zip(tags_ids))
s_time = time.time()
cur.execute("select tag_id, count(*) as count from \
user_tags t_u, user_friend u_f \
where u_f.u_id = %s and \
t_u.u_id = u_f.f_id \
group by tag_id order by count desc limit 10" % u_id)
print time.time()-s_time