-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalytics.py
186 lines (154 loc) · 5.32 KB
/
analytics.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import json
import math
from bson import json_util, ObjectId
from pymongo import MongoClient
import datetime
from bson.code import Code
from datetime import date
from datetime import timedelta
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
DBS_NAME = 'twitter'
COLLECTION_NAME = 'election'
# FIELDS = {'school_state': True, 'resource_type': True, 'poverty_level': True, 'time': True, 'total_donations': True, '_id': False}
connection = MongoClient(MONGODB_HOST, MONGODB_PORT)
collection = connection[DBS_NAME][COLLECTION_NAME]
candidates=['Trump','Clinton','Sanders','Cruz','Bush','Carson','Kasich','Rubio']
def total_data():
return collection.count()
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
def objectIdWithTimestamp(timestamp):
# Convert string date to Date object (otherwise assume timestamp is a date)
if isinstance(timestamp, str):
timestamp = datetime.datetime.strptime(timestamp,"YYYY/MM/DD")
# Convert date object to hex seconds since Unix epoch
hexSeconds = hex(math.floor(unix_time_millis(timestamp)/1000))[2:];
# Create an ObjectId with that hex timestamp
constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
def impact_60000():
result=collection.aggregate([
{'$sort': {'_id':-1}},
{'$limit' : 60000 },
{
'$group':
{
"_id":"$candidate","impact":{"$sum":"$impact"},"score":{"$sum":"$score"},"volume":{"$sum":1}
}
}
])
data = {}
for document in result:
temp={candidates[document.get('_id')]:{'score':document.get('score'),'impact':document.get('impact'),'volume':document.get('volume')}}
data.update(temp)
return data
def impact_240000():
result=collection.aggregate([
{'$sort': {'_id':-1}},
{'$limit' : 240000 },
{
'$group':
{
"_id":"$candidate","impact":{"$sum":"$impact"},"score":{"$sum":"$score"},"volume":{"$sum":1}
}
}
])
data = {}
for document in result:
temp={candidates[document.get('_id')]:{'score':document.get('score'),'impact':document.get('impact'),'volume':document.get('volume')}}
data.update(temp)
return data
def impact():
result=collection.aggregate([
{'$sort': {'_id':-1}},
{'$limit' : 2000000 },
{
'$group':
{
"_id":"$candidate","impact":{"$sum":"$impact"},"score":{"$sum":"$score"},"volume":{"$sum":1}
}
}
])
data = {}
for document in result:
temp={candidates[document.get('_id')]:{'score':document.get('score'),'impact':document.get('impact'),'volume':document.get('volume')}}
data.update(temp)
return data
def impact_lastweek():
timenow = datetime.datetime.now()
last_week = timenow - timedelta(days=7)
result=collection.aggregate([
{'$match':{ '_id': { '$gt': objectIdWithTimestamp(last_week) } }},
{
'$group':
{
"_id":"$candidate","impact":{"$sum":"$impact"},"score":{"$sum":"$score"},"volume":{"$sum":1}
}
}
])
data = {}
for document in result:
temp={candidates[document.get('_id')]:{'score':document.get('score'),'impact':document.get('impact'),'volume':document.get('volume')}}
data.update(temp)
return data
def impact_last3day():
timenow = datetime.datetime.now()
last_day = timenow - timedelta(days=3)
result=collection.aggregate([
{'$match':{ '_id': { '$gt': objectIdWithTimestamp(last_day) } }},
{
'$group':
{
"_id":"$candidate","impact":{"$sum":"$impact"},"score":{"$sum":"$score"},"volume":{"$sum":1}
}
}
])
data = {}
for document in result:
temp={candidates[document.get('_id')]:{'score':document.get('score'),'impact':document.get('impact'),'volume':document.get('volume')}}
data.update(temp)
return data
def impact_lastday():
timenow = datetime.datetime.now()
last_day = timenow - timedelta(days=1)
result=collection.aggregate([
{'$match':{ '_id': { '$gt': objectIdWithTimestamp(last_day) } }},
{
'$group':
{
"_id":"$candidate","impact":{"$sum":"$impact"},"score":{"$sum":"$score"},"volume":{"$sum":1}
}
}
])
data = {}
for document in result:
temp={candidates[document.get('_id')]:{'score':document.get('score'),'impact':document.get('impact'),'volume':document.get('volume')}}
data.update(temp)
return data
# No use for now
def last_hour():
mapper = Code("""
function () {
this.tags.forEach(function(z) {
emit(z, 1);
});
}
""")
reducer = Code("""
function (key, values) {
var total = 0;
for (var i = 0; i < values.length; i++) {
total += values[i];
}
return total;
}
""")
result = collection.map_reduce(mapper, reducer, "myresults",{"candidates.Trump":1})
for doc in result.find():
print(doc)
# timenow = datetime.datetime.now()
# last_week = timenow - timedelta(days=7)
# print(last_week)
# collection.find({ '_id': { '$gt': objectIdWithTimestamp(last_week) } });