-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSearchServiceImpl
552 lines (488 loc) · 18.3 KB
/
SearchServiceImpl
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package com.os.solr.search.service.impl;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.BinaryRequestWriter;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import org.apache.solr.client.solrj.response.TermsResponse;
import org.apache.solr.client.solrj.response.TermsResponse.Term;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SpellingParams;
import org.apache.solr.common.util.NamedList;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.os.search.service.helper.QueryPreparer;
import com.os.solr.search.constants.SearchConstants;
import com.os.solr.search.content.handler.PromotionsHandler;
import com.os.solr.search.custom.solrj.CustomHttpSolrServer;
import com.os.solr.search.custom.solrj.CustomQueryResponse;
import com.os.solr.search.form.SearchForm;
import com.os.solr.search.helper.SearchHelper;
import com.os.solr.search.helper.ServiceHelper;
import com.os.solr.search.helper.URLHelper;
import com.os.solr.search.service.SearchService;
import com.os.solr.search.service.dto.FacetDTO;
import com.os.solr.search.service.dto.ResultsDTO;
import com.os.solr.search.service.dto.SearchResultDTO;
import com.os.solr.search.service.dto.SubCategoryFacetDTO;
import com.os.solr.search.service.dto.SuggestionsDTO;
import com.os.solr.search.service.dto.SynonymDTO;
public class SearchServiceImpl implements SearchService {
private final CustomHttpSolrServer solrServer;
private final Logger logger = LoggerFactory
.getLogger(SearchServiceImpl.class);
public SearchServiceImpl() {
try {
solrServer = new CustomHttpSolrServer(ServiceHelper.getSolrURL());
solrServer.setAllowCompression(true);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public List<SuggestionsDTO> getSuggestions(String keyword) {
if (keyword.trim().isEmpty()) {
return null;
} else {
String[] keys = keyword.split(" ");
List<SuggestionsDTO> autosuggestions = new ArrayList<SuggestionsDTO>();
for (String key : keys) {
if (!key.trim().isEmpty()
&& autosuggestions.size() < SearchConstants.SUGGESTIONS_LIMIT) {
for (SuggestionsDTO suggestion : getHighlightingSuggestions(key)) {
if (autosuggestions.size() < SearchConstants.SUGGESTIONS_LIMIT
&& !autosuggestions.contains(suggestion)) {
autosuggestions.add(suggestion);
} else {
break;
}
}
}
}
return autosuggestions;
}
}
public List<SuggestionsDTO> getHighlightingSuggestions(String keyword) {
try {
SolrQuery query = getHighLightQuery("\"" + keyword + "\"");
QueryResponse queryResponse = solrServer.query(query);
List<SuggestionsDTO> suggestions = getHighlightingTermsFromResponse(
queryResponse, keyword);
if (suggestions == null || suggestions.isEmpty()) {
suggestions = getHighlightSuggest(keyword);
}
return suggestions;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static SolrQuery getHighLightQuery(String keyword) {
SolrQuery query = getKeywordQuery(keyword);
query.setFields(ResultsDTO.PAGE_ID);
query.setRows(200);
query.setHighlight(true).setHighlightSnippets(5);
query.setHighlight(true).setParam("hl.simple.pre", "<b>");
query.setHighlight(true).setParam("hl.simple.post", "</b>");
query.setParam("hl.fl", SearchConstants.SOLR_FIELD_KEYS);
return query;
}
private static SolrQuery getKeywordQuery(String keyword) {
SolrQuery query = new SolrQuery();
StringBuffer suggestQuery = new StringBuffer();
suggestQuery.append(SearchConstants.SOLR_FIELD_KEYS).append(":")
.append(escapeKeyword(keyword.toLowerCase(), false));
query.setQuery(suggestQuery.toString());
query.addFilterQuery(" NOT(" + SearchConstants.SOLR_FIELD_FLAG + ":"
+ SearchConstants.SOLR_FLAG + ")");
query.addFilterQuery(SearchConstants.SOLR_FIELD_ACTIVE + ":"
+ SearchConstants.ACTIVE_FLAG);
return query;
}
private List<SuggestionsDTO> getHighlightingTermsFromResponse(
final CustomQueryResponse queryResponse, final String prefix) {
List<SuggestionsDTO> suggestions = new ArrayList<SuggestionsDTO>();
NamedList<Object> sortedList = queryResponse.getHighlightingInfo();
for (Map.Entry<String, Object> doc : sortedList) {
NamedList<List<String>> fnl = (NamedList<List<String>>) doc
.getValue();
for (Map.Entry<String, List<String>> field : fnl) {
if (field.getValue() != null) {
for (String value : field.getValue()) {
if (value != null) {
if (suggestions.size() == SearchConstants.SUGGESTIONS_LIMIT) {
break;
}
SuggestionsDTO autoSuggest = new SuggestionsDTO();
autoSuggest.setLabel(value);
Matcher matcher = HIGHTLIGHT_PATTERN.matcher(value);
if (matcher.find()) {
value = value.replace("<b>", "");
value = value.replace("</b>", "");
autoSuggest.setValue(value);
}
if (value.toLowerCase().equalsIgnoreCase(
prefix.toLowerCase())
|| suggestions.contains(autoSuggest)) {
continue;
}
suggestions.add(autoSuggest);
}
}
}
}
}
return suggestions;
}
public List<SuggestionsDTO> getHighlightSuggest(String prefix) {
try {
String prefixWithStar = prefix.trim();
if (prefix.trim().contains("\"") || prefix.trim().contains("*"))
prefixWithStar = prefix.replace("*", "").trim();
else
prefixWithStar = prefix.trim() + "*";
SolrQuery query = getHighLightQuery(prefixWithStar);
CustomQueryResponse queryResponse = solrServer.query(query);
solrServer.setParser(new XMLResponseParser());
List<SuggestionsDTO> suggestions = getHighlightingTermsFromResponse(
queryResponse, prefixWithStar);
if (suggestions == null || suggestions.isEmpty()) {
suggestions = getPrefixedFacetSuggestions(prefix);
if (suggestions == null || suggestions.isEmpty()) {
suggestions = spellCheck(prefix);
}
}
return suggestions;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final static String HIGHLIGHTED_SUGGEST_REGEX = "<b>(.*?)</b>";
private final static Pattern HIGHTLIGHT_PATTERN = Pattern.compile(
HIGHLIGHTED_SUGGEST_REGEX, Pattern.CASE_INSENSITIVE);
public List<SuggestionsDTO> getPrefixedFacetSuggestions(String prefix) {
try {
SolrQuery query = getKeywordQuery(prefix);
query.setFields(ResultsDTO.CAT_NAME + "," + ResultsDTO.TITLE);
query.setFacet(true);
query.addFacetField(SearchConstants.SOLR_FIELD_AUTO_SUGGEST_KEYS);
query.setFacetPrefix(prefix);
query.setFacetMinCount(Integer.valueOf(1));
query.setFacetLimit(SearchConstants.SUGGESTIONS_LIMIT);
QueryResponse queryResponse = solrServer.query(query);
return getFacetTermsFromResponse(queryResponse, prefix);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
private List<SuggestionsDTO> getFacetTermsFromResponse(
final CustomQueryResponse queryResponse, final String prefix) {
List<SuggestionsDTO> suggestions = new ArrayList<SuggestionsDTO>();
List<FacetField> fctFields = queryResponse.getFacetFields();
for (FacetField fctfld : fctFields) {
if (fctfld.getValueCount() > 0) {
for (Count c : fctfld.getValues()) {
SuggestionsDTO autoSuggest = new SuggestionsDTO();
if (c != null && !c.getName().equalsIgnoreCase(prefix)) {
autoSuggest.setLabel(c.getName());
autoSuggest.setValue(c.getName());
suggestions.add(autoSuggest);
}
}
}
}
if (suggestions == null || suggestions.isEmpty()) {
suggestions = spellCheck(prefix);
}
return suggestions;
}
public List<SuggestionsDTO> spellCheck(String prefix) {
List<SuggestionsDTO> suggestions = new ArrayList<SuggestionsDTO>();
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(CommonParams.QT, "/spell");
params.set(CommonParams.Q, getKeywordQuery(prefix).getQuery());
params.set(SpellingParams.SPELLCHECK_Q, prefix);
params.set(SpellingParams.SPELLCHECK_COUNT,
SearchConstants.SUGGESTIONS_LIMIT);
params.set("spellcheck", "true");
params.set(SpellingParams.SPELLCHECK_BUILD, "true");
params.set(SpellingParams.SPELLCHECK_EXTENDED_RESULTS, "true");
CustomQueryResponse response;
try {
response = solrServer.query(params);
SpellCheckResponse spellCheckResponse = response
.getSpellCheckResponse();
if (!spellCheckResponse.isCorrectlySpelled()) {
for (Suggestion suggestion : response.getSpellCheckResponse()
.getSuggestions()) {
List<String> alternatives = suggestion.getAlternatives();
if (alternatives != null) {
for (String alternate : alternatives) {
SuggestionsDTO autoSuggest = new SuggestionsDTO();
autoSuggest.setLabel(alternate);
autoSuggest.setValue(alternate);
suggestions.add(autoSuggest);
}
}
}
}
} catch (SolrServerException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
return suggestions;
}
public SearchResultDTO getSearchResults(SearchForm searchForm) {
String keyword = trimWithSpecialCharacters(searchForm.getKeyword());
if (!searchForm.getKeyword().isEmpty() && keyword.trim().isEmpty()) {
SearchResultDTO searchResult = new SearchResultDTO();
searchResult.setResultCount(Long.parseLong("0"));
return searchResult;
} else {
searchForm.setKeyword(keyword);
SearchResultDTO searchResult = new SearchResultDTO();
CustomQueryResponse response = getQueryResponse(searchForm);
if (searchForm.getPageSize() == -1) {
searchForm.setPageSize(Long.valueOf(
response.getResults().getNumFound()).intValue());
response = getQueryResponse(searchForm);
}
searchResult.setResultCount(response.getResults().getNumFound());
searchResult.setResults(fillSearchDetails(response));
searchResult.setCategories(fillFacetDetails(response, searchForm));
return searchResult;
}
}
private List<FacetDTO> fillFacetDetails(CustomQueryResponse response,
SearchForm searchForm) {
List<FacetDTO> resultFacets = new ArrayList<FacetDTO>();
List<FacetField> facets = response.getFacetFields();
if (facets != null && !facets.isEmpty()) {
for (FacetField facet : facets) {
List<FacetField.Count> facetEntries = facet.getValues();
if (facetEntries != null && !facetEntries.isEmpty()) {
FacetDTO catTypeFacets = new FacetDTO();
List<SubCategoryFacetDTO> subCategories = new ArrayList<SubCategoryFacetDTO>();
for (FacetField.Count fcount : facetEntries) {
SubCategoryFacetDTO catFacet = new SubCategoryFacetDTO();
catFacet.setCategoryName(fcount.getName());
catFacet.setCount(fcount.getCount());
subCategories.add(catFacet);
}
catTypeFacets.setSubCategories(subCategories);
resultFacets.add(catTypeFacets);
}
}
}
return resultFacets;
}
private List<ResultsDTO> fillSearchDetails(CustomQueryResponse response) {
List<ResultsDTO> resSet = new ArrayList<ResultsDTO>();
SolrDocumentList sdl = response.getResults();
for (SolrDocument results : sdl) {
ResultsDTO resDTO = new ResultsDTO();
resDTO.setCategoryID(String.valueOf(results
.getFieldValue(ResultsDTO.CAT_ID)));
resDTO.setSearchID(String.valueOf(results
.getFieldValue(ResultsDTO.SEARCH_ID)));
resDTO.setCategoryName(String.valueOf(results
.getFieldValue(ResultsDTO.CAT_NAME)));
resDTO.setTitle(String.valueOf(results
.getFieldValue(ResultsDTO.TITLE)));
resDTO.setDescription(String.valueOf(results
.getFieldValue(ResultsDTO.DESC)));
if (results.getFieldValue(ResultsDTO.STATUS) != null
&& !"".equalsIgnoreCase(results
.getFieldValue(ResultsDTO.STATUS).toString().trim()))
resSet.add(resDTO);
}
return resSet;
}
private CustomQueryResponse getQueryResponse(SearchForm searchForm) {
try {
SolrQuery query = QueryPreparer.prepareQuery(searchForm);
CustomQueryResponse queryResponse = solrServer.query(query);
solrServer.setParser(new XMLResponseParser());
return queryResponse;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
public List<Term> getSimilarKeywords(String keyword) {
List<Term> similarKeywords = new ArrayList<Term>();
List<String> synonyms = getSynonyms(keyword);
for (String simKey : synonyms) {
if (similarKeywords.size() >= SearchConstants.SUGGESTIONS_LIMIT) {
break;
}
if (!simKey.trim().equalsIgnoreCase(keyword.trim())) {
Term term = new Term(simKey, 1);
similarKeywords.add(term);
}
}
if (similarKeywords.isEmpty()) {
List<SuggestionsDTO> suggestions = getSuggestions(keyword);
for (SuggestionsDTO termSuggestion : suggestions) {
if (termSuggestion.getValue() != null
&& !termSuggestion.getValue().equalsIgnoreCase(keyword)) {
Term term = new Term(termSuggestion.getValue(), 1);
similarKeywords.add(term);
}
}
return similarKeywords;
}
}
private List<String> getSynonyms(String keyword) {
List<String> synonyms = new ArrayList<String>();
StringBuffer synonymURL = new StringBuffer(ServiceHelper.getSolrURL());
if (!ServiceHelper.getSolrURL().endsWith("/")
&& !ServiceHelper.getSolrURL().endsWith("\\")) {
synonymURL.append(File.separator);
}
try {
synonymURL.append(SearchConstants.SYNONYMS_FILE_RELATIVE_URL)
.append(URLEncoder.encode(keyword, "UTF-8"));
String serverResponse = URLHelper.getResponse(
synonymURL.toString(), URLHelper.CONTENT_TYPE_XML);
if (!serverResponse.isEmpty()) {
ObjectMapper mapper = new ObjectMapper();
try {
SynonymDTO result = mapper.readValue(serverResponse
.toString().getBytes("UTF-8"), SynonymDTO.class);
synonyms = result.getResponse();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
} catch (UnsupportedEncodingException e1) {
logger.error(e1.getMessage(), e1);
throw new RuntimeException(e1);
}
return synonyms;
}
public List<Term> fetchSimilarKeywords(String keyword) {
List<Term> similarKeywords = new ArrayList<Term>();
SolrQuery query = getKeywordQuery(keyword);
query.addTermsField(SearchConstants.SOLR_FIELD_AUTO_SUGGEST_KEYS);
query.setTerms(true);
query.setTermsSortString("index");
query.setTermsLimit(SearchConstants.TERMS_LIMIT);
query.setTermsPrefix(escapeKeyword(keyword));
query.setTermsSortString("frequency");
query.setQueryType("/terms");
logger.info("Query For Similar Keywords : " + query);
try {
CustomQueryResponse queryResponse = solrServer.query(query);
solrServer.setParser(new XMLResponseParser());
TermsResponse resp = queryResponse.getTermsResponse();
if (resp != null) {
similarKeywords
.addAll(resp
.getTerms(SearchConstants.SOLR_FIELD_AUTO_SUGGEST_KEYS));
if (similarKeywords.size() == 0) {
similarKeywords.addAll(resp
.getTerms(SearchConstants.SOLR_FIELD_KEYS));
}
}
} catch (SolrServerException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
return similarKeywords;
}
@Override
public List<ResultsDTO> getDidYouMeanSearchResults(SearchForm form) {
StringBuffer keywordQuery = new StringBuffer();
if (form.getKeyword() == null
|| form.getKeyword().trim().equalsIgnoreCase("")) {
keywordQuery.append("*:*");
} else {
List<SuggestionsDTO> suggestions = getAutoSuggestionsForZeroSearch(form
.getKeyword());
StringBuffer keys = new StringBuffer();
if (suggestions != null && !suggestions.isEmpty()) {
keys.append(" (");
for (SuggestionsDTO suggest : suggestions) {
keys.append(suggest.getValue() + " ");
}
keys.trimToSize();
if (keys.toString().trim()
.equalsIgnoreCase(form.getKeyword().trim())) {
keys.append("*");
}
keys.append(") ");
getKeywordQuery(keywordQuery, keys.toString());
} else {
String[] splitKeys = form.getKeyword().split(" ");
keys.append(" (");
for (String key : splitKeys) {
if (!key.trim().isEmpty()) {
keys.append(" *" + key.trim() + "* ");
}
}
keys.append(") ");
getKeywordQuery(keywordQuery, keys.toString());
}
}
SolrQuery query = new SolrQuery();
query.setQuery(keywordQuery.toString());
query.addSortField(SearchConstants.SOLR_FIELD_SCORE, ORDER.desc);
query.addSortField(ResultsDTO.RANK_BY_CATEGORY, ORDER.asc);
query.addFilterQuery("NOT(" + SearchConstants.SOLR_FIELD_FLAG + ":"
+ SearchConstants.SOLR_FLAG + ")");
query.addFilterQuery(SearchConstants.SOLR_FIELD_ACTIVE + ":"
+ SearchConstants.ACTIVE_FLAG);
int start = 0;
if (form.getPageSize() == null || form.getPageSize() < 1) {
query.setRows(15);
} else {
query.setRows(form.getPageSize());
}
if (form.getPageNum() != null && form.getPageNum() > 1) {
start = (form.getPageNum() - 1) * form.getPageSize();
}
query.setStart(start);
List<ResultsDTO> searchResult = new ArrayList<ResultsDTO>();
try {
CustomQueryResponse queryResponse = solrServer.query(query);
solrServer.setParser(new XMLResponseParser());
searchResult = fillSearchDetails(queryResponse);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
return searchResult;
}
private static void getKeywordQuery(StringBuffer keywordQuery,
String keyword) {
keywordQuery.append(SearchConstants.SOLR_FIELD_TEXT).append(":")
.append(escapeKeyword(keyword))
.append(" OR ")
// TO FETCH THE COMBINATION OF meaning ful keywords
.append(SearchConstants.SOLR_FIELD_KEY_SETS).append(":")
.append(escapeKeyword(keyword)).append(" OR ")
// Fetch the Synonyms
.append(SearchConstants.SOLR_FIELD_SYNONYM_TEXT).append(":")
.append(escapeKeyword(keyword)).append("");
}
}