-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesdatahandler.py
218 lines (169 loc) · 8.09 KB
/
esdatahandler.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
206
207
208
209
210
211
212
213
214
215
216
217
218
import pandas as pd
from datetime import datetime
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
def anonymize_email(email):
local, domain = email.split('@')
domain_name, extension = domain.split('.')
anonymized_local = local[0] + "*" * (len(local) - 1)
anonymized_domain_name = domain_name[0] + "*" * (len(domain_name) - 1)
anonymized_email = f"{anonymized_local}@{anonymized_domain_name}.{extension}"
return anonymized_email
class ElasticsearchDataHandler:
def __init__(self, es_url, es_api_key, index_name='instructions-demo'):
self.client = Elasticsearch(es_url, api_key=es_api_key)
self.index_name = index_name
def fetch_aggregation_results(self, query):
"""
Executes a search query that includes aggregations and returns the results as a pandas DataFrame.
Parameters:
- query (string): KQL query to execute.
"""
response = self.client.search(index=self.index_name, body=query)
buckets = response["aggregations"]["results"]["buckets"]
return pd.DataFrame(buckets).sort_values(by='doc_count')
def calculate_progress(self, selected_script):
"""
Calculates the progress of selected instruction subset (selected_script).
It uses a predefined KQL query to aggregate document statuses and returns calculated progress as a fraction.
Parameters:
- selected_script (string): value for 'script' field in Elsticsearch instruction metadata defining instructions subset.
"""
progress_query = {
"size": 0,
"query": {
"bool": {
"filter": [
{
"term": {
"meta.script.keyword": selected_script
}
}
]
}
},
"aggs": {
"results": {
"terms": {
"field": "status.keyword" }
}
}
}
df = self.fetch_aggregation_results(progress_query)
total_docs = df['doc_count'].sum()
total_except_new = df[df['key'] != 'new']['doc_count'].sum()
return total_except_new / total_docs if total_docs else 0
def leaderboard_df(self, selected_script):
"""
Creates a leaderboard DataFrame from Elasticsearch data based on the updated_by field.
This function anonymizes email addresses in the 'key' column, making it suitable for public display of user contributions.
Parameters:
- selected_script (string): value for 'script' field in Elsticsearch instruction metadata defining instructions subset.
"""
leaders_query = {
"size": 0,
"query": {
"bool": {
"filter": [
{
"term": {
"meta.script.keyword": selected_script
}
}
]
}
},
"aggs": {
"results": {
"terms": {
"field": "updated_by.keyword"
}
}
}
}
df = self.fetch_aggregation_results(leaders_query)
df['key'] = df['key'].apply(lambda x: anonymize_email(x) if '@' in x and '.' in x else x)
return df.sort_values(by='doc_count', ascending=True)
def get_next_document(self, selected_script, nickname):
"""
Fetches the next instruction document marked as 'new' for a selected instruction subset and updates its status to 'in progress'. Retruns json.
Parameters:
- selected_script (string): value for 'script' field in Elsticsearch instruction metadata defining instructions subset.
- nickname (string): username value to save in updated_by field of instruction document.
"""
search = Search(using=self.client, index=self.index_name).query("bool", must=[{"match": {"status": "new"}}, {"match": {"meta.script.keyword": selected_script}}]).sort("_doc")[:1]
response = search.execute()
if response.hits.total.value > 0:
document = response[0]
self.update_document_status(document.meta.id, "in progress", nickname)
return document
return None
def update_document_status(self, doc_id, status, nickname):
"""
Updates the status and last_modified value of a selected instruction document and optionally the nickname of the user who updated it.
Parameters:
- doc_id (string): unique Elasticsearch document identifier
- status (string): status value to set. 'ok', 'not ok', 'in progress'
- nickname (string): username value to save in updated_by field of instruction document.
"""
update_body = {"doc": {"status": status, "last_modified": datetime.now().isoformat()}}
if nickname:
update_body["doc"]["updated_by"] = nickname
self.client.update(index=self.index_name, id=doc_id, body=update_body)
def update_document(self, doc_id, update_body):
"""
Allows for arbitrary updates to a instruction document using a specified update body json.
Parameters:
- doc_id (string): unique Elasticsearch document identifier
- update_body: json with new values for instruction fields.
"""
self.client.update(index=self.index_name, id=doc_id, body=update_body)
def get_scripts(self):
"""
Fetches and returns a list of unique script field values from all documents in index.
Parameters:
- doc_id (string): unique Elasticsearch document identifier
- update_body: json with new values for instrunction fields.
"""
scripts_query = {
"size": 0,
"aggs": {
"unique_scripts": {
"terms": {
"field": "meta.script.keyword",
"size": 1000
}
}
}
}
response = self.client.search(index=self.index_name, body=scripts_query)
unique_scripts = [bucket['key'] for bucket in response['aggregations']['unique_scripts']['buckets']]
return unique_scripts
def get_instructions(self):
"""
Fetches all instructions from an Elasticsearch index where status field value is 'ok',
returning only the 'instruction' part of each document.
"""
page = self.client.search(
index=self.index_name,
scroll='5m',
size=10000,
query={
"bool": {
"must": [
{
"term": {
"status.keyword": "ok"
}
}
]
}
})
scroll_id = page['_scroll_id']
all_instructions = [hit['_source']['instruction'] for hit in page['hits']['hits']]
while len(page['hits']['hits']):
page = self.client.scroll(scroll_id=scroll_id, scroll='2m')
scroll_id = page['_scroll_id']
all_instructions.extend(hit['_source']['instruction'] for hit in page['hits']['hits'])
self.client.clear_scroll(scroll_id=scroll_id)
return all_instructions