-
Notifications
You must be signed in to change notification settings - Fork 2
/
query_mongo.py
186 lines (150 loc) · 6.48 KB
/
query_mongo.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
#!/usr/bin/env python3
#
# author: Gary A. Stafford
# site: https://programmaticponderings.com
# license: MIT License
# purpose: Perform queries against MongoDB
# USAge: python3 ./query_mongo.py
import pymongo
import os
mongodb_conn = os.environ.get('MONOGDB_CONN')
mongodb_client = pymongo.MongoClient(mongodb_conn)
mongo_db = mongodb_client['movies']
mongo_collection = mongo_db['movieDetails']
def main():
print('Target MongoDB instance: %s' % mongodb_conn)
create_indexes()
# Query 1a: All Documents
find_documents({})
# Query 1b: Count Only
count_documents()
# Query 2: Exact Search
find_documents({'title': 'Star Wars: Episode V - The Empire Strikes Back'})
# Query 3: Search Phrase
find_documents({'title': {'$regex': r'\bstar wars\b', '$options': 'i'}})
# Query 4: Search Terms
# find_documents({'title': {'$regex': 'star|wars', '$options': 'i'}})
find_documents({'$text': {'$search': 'star wars',
'$language': 'en',
'$caseSensitive': False},
'countries': 'USA'},
[('score', {'$meta': 'textScore'})],
projection={'score': {'$meta': 'textScore'}, '_id': 0, 'title': 1})
# Query 5a: Multiple Search Terms
find_documents({'genres': {'$in': ['Adventure', 'Action', 'Western']}, 'countries': 'USA'},
projection={'_id': 0, 'genres': 1, 'title': 1})
# modify index
modify_index()
# Query 6a
find_documents({'$text': {'$search': 'western action adventure',
'$language': 'en',
'$caseSensitive': False},
'countries': 'USA'},
[('score', {'$meta': 'textScore'})],
projection={'score': {'$meta': 'textScore'}, '_id': 0, 'genres': 1, 'title': 1})
weight_index()
# Query 6b: Boosting Fields
find_documents({'$text': {'$search': 'western action adventure',
'$language': 'en',
'$caseSensitive': False},
'countries': 'USA'},
[('score', {'$meta': 'textScore'})],
projection={'score': {'$meta': 'textScore'}, '_id': 0, 'genres': 1, 'title': 1})
# # Additional Unused Query Variations
# find_documents({'$text': {'$search': 'Star Wars: Episode V - The Empire Strikes Back',
# '$language': 'en',
# '$caseSensitive': False},
# 'countries': 'USA'},
# [('score', {'$meta': 'textScore'})],
# projection={'score': {'$meta': 'textScore'}, '_id': 0, 'title': 1})
# find_documents({'title': {'$regex': r'\bstar wars\b|\bstar trek\b', '$options': 'i'}})
#
# find_documents({'plot': {'$regex': r'\bwestern\b|\baction\b|\badventure\b', '$options': 'i'},
# 'countries': 'USA'})
#
# find_documents({'plot': {'$regex': 'western|action|adventure', '$options': 'i'},
# 'countries': 'USA'})
#
# find_documents({'title': {'$regex': r'\bstar\b|\bwars\b', '$options': 'i'}})
#
# find_documents({'$or': [{'title': {'$regex': r'\bwestern\b|\baction\b|\adventure\b', '$options': 'i'}},
# {'plot': {'$regex': r'\bwestern\b|\baction\b|\adventure\b', '$options': 'i'}},
# {'genres': {'$regex': r'\bwestern\b|\baction\b|\adventure\b', '$options': 'i'}}],
# 'countries': 'USA'})
#
# find_documents({'$or': [{'title': {'$regex': 'western|action|adventure', '$options': 'i'}},
# {'plot': {'$regex': 'western|action|adventure', '$options': 'i'}},
# {'genres': {'$regex': 'western|action|adventure', '$options': 'i'}}],
# 'countries': 'USA'})
def create_indexes():
try:
mongo_collection.drop_index('genres_text_title_text_plot_text')
except pymongo.errors.OperationFailure:
print('No index to remove')
try:
mongo_collection.drop_index('title_text')
except pymongo.errors.OperationFailure:
print('No index to remove')
try:
mongo_collection.drop_index('countries_1')
except pymongo.errors.OperationFailure:
print('No index to remove')
try:
mongo_collection.drop_index('title_1')
except pymongo.errors.OperationFailure:
print('No index to remove')
mongo_collection.create_index([('title', pymongo.ASCENDING)])
mongo_collection.create_index([('countries', pymongo.ASCENDING)])
mongo_collection.create_index([('title', pymongo.TEXT)])
def modify_index():
try:
mongo_collection.drop_index('title_text')
except pymongo.errors.OperationFailure:
print('No index to remove')
mongo_collection.create_index([('genres', pymongo.TEXT),
('title', pymongo.TEXT),
('plot', pymongo.TEXT)])
def weight_index():
try:
mongo_collection.drop_index('genres_text_title_text_plot_text')
except pymongo.errors.OperationFailure:
print('No index to remove')
mongo_collection.create_index([('genres', pymongo.TEXT),
('title', pymongo.TEXT),
('plot', pymongo.TEXT)],
weights={'genres': 4, 'title': 2})
def find_documents(query, *sort, projection={'_id': 0, 'title': 1}):
if sort:
documents = mongo_collection \
.find(query, projection) \
.sort(*sort) \
.limit(5)
else:
documents = mongo_collection \
.find(query, projection) \
.limit(5)
print("----------\n")
print("Parameters\n----------")
# print(documents.explain())
print("query: %s" % query)
print("projection: %s" % projection)
try:
print("sort: %s" % sort)
except TypeError:
print("sort: %s" % "none")
print("\nResults\n----------")
print("document count: %s" % documents.count())
for document in documents:
if 'score' in document:
document['score'] = round(document['score'], 2)
print(document)
def count_documents():
count = mongo_collection.count()
print("----------\n")
print("Parameters\n----------")
# print(documents.explain())
print("query: {}")
print("\nResults\n----------")
print("document count: %s" % count)
if __name__ == "__main__":
main()