-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelasticsearch_operations.py
297 lines (257 loc) · 8.96 KB
/
elasticsearch_operations.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import numpy as np
import tensorflow_hub as hub
from elasticsearch import Elasticsearch, helpers
import preprocessing
import os
es = Elasticsearch([{'host': 'localhost', 'port': '9200'}])
def check_if_index_exist(index):
return es.indices.exists(index=index)
def upload_data_to_elastic():
# Change the filepath to your filepath
df = preprocessing.read_csv()
# Drop all unused columns
columns_to_drop = ["book_edition", "book_format", "image_url", "book_rating_count", "book_review_count",
"book_pages"]
df = preprocessing.drop_columns(df, columns_to_drop)
df = preprocessing.drop_no_english_sentences(df)
df = preprocessing.remove_stopwords(df)
# Transform the DataFrame to json string
parsed = preprocessing.load_json(df)
=======
es = Elasticsearch([{'host': 'localhost', 'port': '9200'}])
default_index = 'books_default_index'
universal_index_name = 'book_universal'
tf_idf_index_name = "books_tf_idf"
url = "https://tfhub.dev/google/universal-sentence-encoder/4"
model = hub.load("../model")
csv_path = " "
def create_indices(path_to_preprocessed_csv = "./preprocessed_book_data_final.csv",
path_to_original_csv="./book_data.csv"):
global csv_path
if not es.ping():
raise ValueError("Connection failed")
if os.path.isfile(path_to_preprocessed_csv):
print("Preprocessed file exists")
csv_path = path_to_preprocessed_csv
else:
if not os.path.isfile(path_to_original_csv):
print("Please provide the application with the original dataset")
return
else:
print("Preprocessing the original file. This will take some time...")
df = preprocessing.read_csv(path_to_original_csv)
df = preprocessing.drop_columns(df)
df = preprocessing.remove_not_null(df)
df = preprocessing.remove_non_english_words(df)
df = preprocessing.drop_no_english_sentences(df) # language detect
df = preprocessing.remove_stopwords_lemmetize(df)
csv_path = path_to_preprocessed_csv
preprocessing.save_to_csv(df, csv_path)
if not es.indices.exists(default_index):
upload_to_default_index()
if not es.indices.exists(tf_idf_index_name):
upload_to_elasticsearch_with_tf_idf()
if not es.indices.exists(universal_index_name):
upload_to_elasticsearch_with_universal()
return True
def create_tf_idf_index():
# Define the index mapping
config = {
"settings": {
"number_of_shards": 1,
"similarity": {
"scripted_tfidf": {
"type": "scripted",
"script": {
"source": "double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;"
}
}
}
},
"mappings": {
"properties": {
"book_authors": {
"type": "text",
"similarity": "scripted_tfidf"
},
"book_desc": {
"type": "text",
"similarity": "scripted_tfidf"
},
"book_isbn": {
"type": "text"
},
"book_rating": {
"type": "float"
},
"book_title": {
"type": "text",
"similarity": "scripted_tfidf"
},
"genres": {
"type": "text"
},
"book_desc_original": {
"type": "text"
}
}
}
}
try:
# Create the index if not exists
if not es.indices.exists(tf_idf_index_name):
# Ignore 400 means to ignore "Index Already Exist" error.
es.indices.create(
index=tf_idf_index_name, body=config
)
print("Created Index -> ", tf_idf_index_name)
else:
print("Index " + tf_idf_index_name + " exists...")
except Exception as ex:
print(str(ex))
def create_universal_index():
# Define the index mapping
mapping = {
"mappings": {
"properties": {
"book_authors": {
"type": "text" # formerly "string"
},
"book_desc": {
"type": "text" # formerly "string"
},
"book_isbn": {
"type": "text"
},
"book_rating": {
"type": "float"
},
"book_title": {
"type": "text"
},
"genres": {
"type": "text"
},
"book_desc_original": {
"type": "text"
},
"desc_vec_dense": {
"type": "dense_vector",
"dims": 512
},
}
}
}
try:
# Create the index if not exists
if not es.indices.exists(universal_index_name):
# Ignore 400 means to ignore "Index Already Exist" error.
es.indices.create(
index=universal_index_name, body=mapping # ignore=[400, 404]
)
print("Created Index -> ", universal_index_name)
else:
print("Index book test exists...")
except Exception as ex:
print(str(ex))
def upload_to_default_index():
df = preprocessing.read_csv(csv_path)
df.dropna(inplace=True, subset=["book_desc"])
parsed = preprocessing.load_json(df)
es.indices.create(default_index)
print("Created Index -> ", default_index)
upload_data_to_elastic(parsed, default_index)
print("\n Uploaded to elasticsearch with index", default_index)
def upload_to_elasticsearch_with_tf_idf():
df = preprocessing.read_csv(csv_path)
df.dropna(inplace=True, subset=["book_desc"])
parsed = preprocessing.load_json(df)
create_tf_idf_index()
upload_data_to_elastic(parsed, tf_idf_index_name)
print("\n Uploaded to elasticsearch with index", tf_idf_index_name)
def upload_to_elasticsearch_with_universal():
df = preprocessing.read_csv(csv_path)
df.dropna(inplace=True, subset=["book_desc"])
df['desc_vec_dense'] = df['book_desc'].apply(lambda x: np.squeeze(np.asarray(model([x])[0])))
parsed = preprocessing.load_json(df)
create_universal_index()
upload_data_to_elastic(parsed, universal_index_name)
print("\n Uploaded to elasticsearch with index", universal_index_name)
def upload_data_to_elastic(parsed, index_name):
entries = []
for i in range(0, len(parsed['data'])):
source = parsed['data'][i]
entry = {
"_index": index_name,
"_id": i,
"_source": source
}
entries.append(entry)
if len(entries) >= 50:
helpers.bulk(es, entries)
entries = []
if len(entries) > 0:
helpers.bulk(es, entries)
def search_in_elasticsearch(search_term):
res = es.search(
index="books",
size=20,
def search_in_elasticsearch_with_default_index(search_term):
result = es.search(
index=default_index,
body={
"query": {
"multi_match": {
"query": search_term,
"fields": [
"book_authors",
"book_desc",
"book_title"
]
}
}
}
)
for res in result['hits']['hits']:
print(res['_score'])
return result
def search_in_elasticsearch_with_tf_idf(search_term):
result = es.search(
index="books_tf_idf",
>>>>>>> latest_version
body={
"query": {
"multi_match": {
"query": search_term,
"fields": [
"book_authors",
"book_desc",
"book_title"
]
}
}
}
)
return res
def search_in_elasticsearch_with_universal_index(search_term):
query_vector = np.squeeze(np.asarray(model([search_term])))
s_body = {
"query": {
"script_score": {
"query": {
"match_all": {}
},
"script": {
"source": "cosineSimilarity(params.queryVector, 'desc_vec_dense') + 1.0",
"params": {
"queryVector": query_vector
}
}
}
}
}
# Semantic vector search with cosine similarity
result = es.search(index=universal_index_name, body=s_body)
for res in result['hits']['hits']:
print(res['_score'])
return result