forked from simon987/Simple-Incremental-Search-Tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
205 lines (155 loc) · 5.91 KB
/
search.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import json
import os
import elasticsearch
import requests
from elasticsearch import helpers
import config
class Search:
def __init__(self, index: str):
self.index_name = index
self.es = elasticsearch.Elasticsearch()
try:
requests.head(config.elasticsearch_url)
except:
print("elasticsearch is not running!")
self.search_iterator = None
def get_all_documents(self, dir_id: int):
return helpers.scan(client=self.es,
query={"_source": {"includes": ["path", "name", "mime", "extension"]},
"query": {"term": {"directory": dir_id}}},
index=self.index_name)
def get_index_size(self):
try:
info = requests.get("http://localhost:9200/" + self.index_name + "/_stats")
if info.status_code == 200:
parsed_info = json.loads(info.text)
return int(parsed_info["indices"][self.index_name]["total"]["store"]["size_in_bytes"])
except:
return 0
def get_doc_count(self):
try:
info = requests.get("http://localhost:9200/" + self.index_name + "/_stats")
if info.status_code == 200:
parsed_info = json.loads(info.text)
return int(parsed_info["indices"][self.index_name]["total"]["docs"]["count"])
except:
return 0
def get_doc_size(self):
try:
query = self.es.search(body={
"aggs": {
"total_size": {
"sum": {"field": "size"}
}
}
})
return query["aggregations"]["total_size"]["value"]
except:
return 0
def get_mime_types(self):
query = self.es.search(body={
"aggs": {
"mimeTypes": {
"terms": {
"field": "mime",
"size": 10000
}
}
}
})
return query["aggregations"]["mimeTypes"]["buckets"]
def get_mime_map(self):
mime_map = []
for mime in self.get_mime_types():
splited_mime = os.path.split(mime["key"])
child = dict()
child["text"] = splited_mime[1] + " (" + str(mime["doc_count"]) + ")"
child["id"] = mime["key"]
mime_category_exists = False
for category in mime_map:
if category["text"] == splited_mime[0]:
category["children"].append(child)
mime_category_exists = True
break
if not mime_category_exists:
mime_map.append({"text": splited_mime[0], "children": [child]})
return mime_map
def search(self, query, size_min, size_max, mime_types, must_match, directories, path):
condition = "must" if must_match else "should"
filters = [
{"range": {"size": {"gte": size_min, "lte": size_max}}},
{"terms": {"directory": directories}}
]
if path != "":
filters.append({"term": {"path": path}})
if mime_types != "any":
filters.append({"terms": {"mime": mime_types}})
page = self.es.search(body={
"query": {
"bool": {
condition: {
"multi_match": {
"query": query,
"fields": ["name^3", "name.nGram^2", "content", "album^4", "artist^4", "title^4", "genre",
"album_artist^4", "font_name^2"],
"operator": "or"
}
},
"filter": filters
}
},
"sort": [
"_score"
],
"highlight": {
"fields": {
"content": {"pre_tags": ["<mark>"], "post_tags": ["</mark>"]},
"name": {"pre_tags": ["<mark>"], "post_tags": ["</mark>"]},
"name.nGram": {"pre_tags": ["<mark>"], "post_tags": ["</mark>"]},
"font_name": {"pre_tags": ["<mark>"], "post_tags": ["</mark>"]},
}
},
"aggs": {
"total_size": {"sum": {"field": "size"}}
},
"size": 40}, index=self.index_name, scroll="15m")
return page
def suggest(self, prefix):
suggestions = self.es.search(body={
"suggest": {
"path": {
"prefix": prefix,
"completion": {
"field": "suggest-path",
"skip_duplicates": True,
"size": 10000
}
}
}
})
path_list = []
if "suggest" in suggestions:
for option in suggestions["suggest"]["path"][0]["options"]:
path_list.append(option["_source"]["path"])
return path_list
def scroll(self, scroll_id):
page = self.es.scroll(scroll_id=scroll_id, scroll="3m")
return page
def get_doc(self, doc_id):
try:
return self.es.get(index=self.index_name, id=doc_id, doc_type="file")
except elasticsearch.exceptions.NotFoundError:
return None
def delete_directory(self, dir_id):
while True:
try:
self.es.delete_by_query(body={"query": {
"bool": {
"filter": {"term": {"directory": dir_id}}
}
}}, index=self.index_name, request_timeout=60)
break
except elasticsearch.exceptions.ConflictError:
print("Error: multiple delete tasks at the same time")
except Exception as e:
print(e)