-
Notifications
You must be signed in to change notification settings - Fork 3
/
mongo_search_healthcare.py
77 lines (60 loc) · 2.37 KB
/
mongo_search_healthcare.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
## These are some simple search queries on the mongoDB database.
## It can be queried in real-time as the streaming twitter API is loading more data.
def get_db(db_name):
from pymongo import MongoClient
client = MongoClient('localhost:27017')
db = client[db_name]
return db
## Find top locations
def location_pipeline():
pipeline = [{"$group": {"_id": "$place.country",
"count": {"$sum": 1}}},
{"$sort": {"count": -1}},
{"$limit": 10}]
return pipeline
## Find top hashtags. Unwind is used to drill into the hashtags nested array, then group all individual hashtags, and count them.
## Leaving out unwind, you can aggregate the groups of hashtags by each user/tweet as an individual entity to be counted instead.
def hashtag_pipeline():
pipeline = [{"$unwind": "$entities.hashtags"},
{"$group": {"_id": "$entities.hashtags",
"count": {"$sum": 1}}},
{"$sort": {"count": -1}},
{"$limit": 10}]
return pipeline
## Find tweets from US, define what to return in 'project'
def project_matches_pipeline():
pipeline = [{"$match": {"place.country": "United States"}},
{"$project": {"country": "$place.country",
"screen_name": "$user.screen_name",
"tweet": "$text",
"hashtags": "$entities.hashtags"}},
{"$sort": {"hashtags": -1}},
{"$limit": 1}]
return pipeline
## Here is where the defined pipelines get sent to process.
def aggregate(db, pipeline):
result = db.twitter_healthcare.aggregate(pipeline)
return result
if __name__ == '__main__':
db = get_db('twitter')
location = location_pipeline()
result = aggregate(db, location)
print "Printing the top 10 locations of tweets:"
import pprint
pprint.pprint(result)
print ""
hashtag = hashtag_pipeline()
result = aggregate(db, hashtag)
print "Printing the top 10 hashtags:"
import pprint
pprint.pprint(result)
print ""
matches = project_matches_pipeline()
result = aggregate(db, matches)
print "Printing the matched records:"
import pprint
pprint.pprint(result)
print ""
#pprint.pprint(result["result"][0])
#pprint.pprint(db.twitterDB.find_one())
#print ""