source: gs3-extensions/solr/trunk/src/src/java/org/greenstone/gsdl3/service/GS2SolrSearch.java@ 32086

Last change on this file since 32086 was 32086, checked in by kjdon, 6 years ago

added code to deal with storing any displayItems for the facets, then using those to return a displayItem with any resulting facet info for a query

  • Property svn:executable set to *
File size: 19.1 KB
Line 
1/*
2 * GS2SolrSearch.java
3 * Copyright (C) 2006 New Zealand Digital Library, http://www.nzdl.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19package org.greenstone.gsdl3.service;
20
21import java.io.File;
22import java.io.IOException;
23// Greenstone classes
24import java.util.ArrayList;
25import java.util.HashMap;
26import java.util.Iterator;
27import java.util.List;
28import java.util.Map;
29import java.util.Properties;
30import java.util.Set;
31import java.util.Vector;
32
33import org.apache.log4j.Logger;
34import org.apache.solr.client.solrj.SolrServer;
35import org.apache.solr.client.solrj.SolrServerException;
36import org.apache.solr.client.solrj.impl.HttpSolrServer;
37import org.apache.solr.client.solrj.impl.HttpSolrServer.RemoteSolrException;
38import org.apache.solr.client.solrj.request.CoreAdminRequest;
39import org.apache.solr.client.solrj.response.CoreAdminResponse;
40import org.apache.solr.client.solrj.response.FacetField;
41import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
42import org.apache.solr.common.util.NamedList;
43import org.greenstone.LuceneWrapper4.SharedSoleneQueryResult;
44import org.greenstone.gsdl3.util.FacetWrapper;
45import org.greenstone.gsdl3.util.GSFile;
46import org.greenstone.gsdl3.util.GSXML;
47import org.greenstone.gsdl3.util.SolrFacetWrapper;
48import org.greenstone.gsdl3.util.SolrQueryResult;
49import org.greenstone.gsdl3.util.SolrQueryWrapper;
50import org.greenstone.util.GlobalProperties;
51import org.w3c.dom.Document;
52import org.w3c.dom.Element;
53import org.w3c.dom.NodeList;
54
55import org.apache.solr.client.solrj.impl.HttpSolrServer.RemoteSolrException;
56import org.apache.solr.client.solrj.request.CoreAdminRequest;
57import org.apache.solr.client.solrj.response.CoreAdminResponse;
58import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
59import org.apache.solr.common.util.NamedList;
60
61public class GS2SolrSearch extends SharedSoleneGS2FieldSearch
62{
63
64 public static final String SOLR_SERVLET_SUFFIX = "/solr";
65 protected static final String SORT_ORDER_PARAM = "sortOrder";
66 protected static final String SORT_ORDER_DESCENDING = "1";
67 protected static final String SORT_ORDER_ASCENDING = "0";
68
69 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.service.GS2SolrSearch.class.getName());
70
71 protected String solr_servlet_base_url;
72 protected HashMap<String, SolrServer> solr_core_cache;
73 protected SolrQueryWrapper solr_src = null;
74
75 protected ArrayList<String> _facets = new ArrayList<String>();
76 protected HashMap<String, Element> _facet_display_names = new HashMap<String, Element>();
77
78 public GS2SolrSearch()
79 {
80 paramDefaults.put(SORT_ORDER_PARAM, SORT_ORDER_DESCENDING);
81 does_faceting = true;
82 does_highlight_snippets = true;
83 does_full_field_highlighting = true;
84 // Used to store the solr cores that match the required 'level'
85 // of search (e.g. either document-level=>didx, or
86 // section-level=>sidx. The hashmap is filled out on demand
87 // based on 'level' parameter passed in to 'setUpQueryer()'
88
89 solr_core_cache = new HashMap<String, SolrServer>();
90
91 this.solr_src = new SolrQueryWrapper();
92
93 // Create the solr servlet url on GS3's tomcat. By default it's "http://localhost:8383/solr"
94 // Don't do this in configure(), since the tomcat url will remain unchanged while tomcat is running
95 try {
96 Properties globalProperties = new Properties();
97 globalProperties.load(Class.forName("org.greenstone.util.GlobalProperties").getClassLoader().getResourceAsStream("global.properties"));
98 String host = globalProperties.getProperty("tomcat.server", "localhost");
99 String port = globalProperties.getProperty("tomcat.port", "8383");
100 String protocol = globalProperties.getProperty("tomcat.protocol", "http");
101
102 String portStr = port.equals("80") ? "" : ":"+port;
103 solr_servlet_base_url = protocol+"://"+host+portStr+SOLR_SERVLET_SUFFIX;
104 } catch(Exception e) {
105 logger.error("Error reading greenstone's tomcat solr server properties from global.properties", e);
106 }
107 }
108
109 /** configure this service */
110 public boolean configure(Element info, Element extra_info)
111 {
112 boolean success = super.configure(info, extra_info);
113
114 // clear the map of solr cores for this collection added to the map upon querying
115 solr_core_cache.clear();
116
117 if(!success) {
118 return false;
119 }
120
121 // Setting up facets
122
123 // the search element from collectionConfig
124 Element searchElem = (Element) GSXML.getChildByTagName(extra_info, GSXML.SEARCH_ELEM);
125
126 Document owner = info.getOwnerDocument();
127 // for each facet in buildConfig
128 NodeList facet_list = info.getElementsByTagName("facet");
129 for (int i=0; i<facet_list.getLength(); i++) {
130 Element facet = (Element)facet_list.item(i);
131 String shortname = facet.getAttribute(GSXML.SHORTNAME_ATT);
132 _facets.add(shortname);
133
134 // now add any displayItems into the facet element
135 // (which is stored as part of info), then we can add to
136 // the result if needed
137 String longname = facet.getAttribute(GSXML.NAME_ATT);
138 Element config_facet = GSXML.getNamedElement(searchElem, "facet", GSXML.NAME_ATT, longname);
139 if (config_facet != null) {
140 NodeList display_items = config_facet.getElementsByTagName(GSXML.DISPLAY_TEXT_ELEM);
141 for (int j=0; j<display_items.getLength(); j++) {
142 Element e = (Element) display_items.item(j);
143 facet.appendChild(owner.importNode(e, true));
144 }
145 _facet_display_names.put(shortname, facet);
146
147 }
148
149 }
150
151 //If use Solr check if cores loaded
152 if (!loadSolrCores()) {
153 logger.error("Collection: couldn't configure collection: " + this.cluster_name + ", "
154 + "Couldn't activate Solr cores");
155 return false;
156 }
157 // NodeList configIndexElems = searchElem.getElementsByTagName(GSXML.INDEX_ELEM);
158
159 // ArrayList<String> chosenFacets = new ArrayList<String>();
160 // for (int i = 0; i < configIndexElems.getLength(); i++)
161 // {
162 // Element current = (Element) configIndexElems.item(i);
163 // if (current.getAttribute(GSXML.FACET_ATT).equals("true"))
164 // {
165 // chosenFacets.add(current.getAttribute(GSXML.NAME_ATT));
166 // }
167 // }
168
169 // Element indexListElem = (Element) GSXML.getChildByTagName(info, GSXML.INDEX_ELEM + GSXML.LIST_MODIFIER);
170 // NodeList buildIndexElems = indexListElem.getElementsByTagName(GSXML.INDEX_ELEM);
171
172 // for (int j = 0; j < buildIndexElems.getLength(); j++)
173 // {
174 // Element current = (Element) buildIndexElems.item(j);
175 // for (int i = 0; i < chosenFacets.size(); i++)
176 // {
177 // if (current.getAttribute(GSXML.NAME_ATT).equals(chosenFacets.get(i)))
178 // {
179 // _facets.add(current.getAttribute(GSXML.SHORTNAME_ATT));
180 // }
181 // }
182 // }
183
184 return true;
185 }
186
187 public void cleanUp()
188 {
189 super.cleanUp();
190 this.solr_src.cleanUp();
191
192 // clear the map keeping track of the SolrServers in this collection
193 solr_core_cache.clear();
194 }
195
196 /** add in the SOLR specific params to TextQuery */
197 protected void addCustomQueryParams(Element param_list, String lang)
198 {
199 super.addCustomQueryParams(param_list, lang);
200 /** Add in the sort order asc/desc param */
201 createParameter(SORT_ORDER_PARAM, param_list, lang);
202 }
203 /** add in SOLR specific params for AdvancedFieldQuery */
204 protected void addCustomQueryParamsAdvField(Element param_list, String lang)
205 {
206 super.addCustomQueryParamsAdvField(param_list, lang);
207 createParameter(SORT_ORDER_PARAM, param_list, lang);
208
209 }
210 /** create a param and add to the list */
211 protected void createParameter(String name, Element param_list, String lang)
212 {
213 Document doc = param_list.getOwnerDocument();
214 Element param = null;
215 String param_default = paramDefaults.get(name);
216 if (name.equals(SORT_ORDER_PARAM)) {
217 String[] vals = { SORT_ORDER_ASCENDING, SORT_ORDER_DESCENDING };
218 String[] vals_texts = { getTextString("param." + SORT_ORDER_PARAM + "." + SORT_ORDER_ASCENDING, lang), getTextString("param." + SORT_ORDER_PARAM + "." + SORT_ORDER_DESCENDING, lang) };
219
220 param = GSXML.createParameterDescription(doc, SORT_ORDER_PARAM, getTextString("param." + SORT_ORDER_PARAM, lang), GSXML.PARAM_TYPE_ENUM_SINGLE, param_default, vals, vals_texts);
221 }
222
223 if (param != null)
224 {
225 param_list.appendChild(param);
226 }
227 else
228 {
229 super.createParameter(name, param_list, lang);
230 }
231
232 }
233
234 /** methods to handle actually doing the query */
235
236 /** do any initialisation of the query object */
237 protected boolean setUpQueryer(HashMap params)
238 {
239 this.solr_src.clearFacets();
240 this.solr_src.clearFacetQueries();
241
242 for (int i = 0; i < _facets.size(); i++)
243 {
244 this.solr_src.addFacet(_facets.get(i));
245 }
246
247 String index = "didx";
248 if (this.default_level.toUpperCase().equals("SEC")) {
249 index = "sidx";
250 }
251 String physical_index_language_name = null;
252 String physical_sub_index_name = null;
253 int maxdocs = 100;
254 int hits_per_page = 20;
255 int start_page = 1;
256 // set up the query params
257 Set entries = params.entrySet();
258 Iterator i = entries.iterator();
259 while (i.hasNext())
260 {
261 Map.Entry m = (Map.Entry) i.next();
262 String name = (String) m.getKey();
263 String value = (String) m.getValue();
264
265 ///System.err.println("### GS2SolrSearch.java: name " + name + " - value " + value);
266
267 if (name.equals(MAXDOCS_PARAM) && !value.equals(""))
268 {
269 maxdocs = Integer.parseInt(value);
270 }
271 else if (name.equals(HITS_PER_PAGE_PARAM))
272 {
273 hits_per_page = Integer.parseInt(value);
274 }
275 else if (name.equals(START_PAGE_PARAM))
276 {
277 start_page = Integer.parseInt(value);
278 }
279 else if (name.equals(MATCH_PARAM))
280 {
281 if (value.equals(MATCH_PARAM_ALL))
282 {
283 this.solr_src.setDefaultConjunctionOperator("AND");
284 }
285 else
286 {
287 this.solr_src.setDefaultConjunctionOperator("OR");
288 }
289 }
290 else if (name.equals(RANK_PARAM))
291 {
292 if (value.equals(RANK_PARAM_RANK))
293 {
294 value = SolrQueryWrapper.SORT_BY_RANK;
295 } else if (value.equals(RANK_PARAM_NONE)) {
296 value = SolrQueryWrapper.SORT_BY_INDEX_ORDER;
297 }
298
299 this.solr_src.setSortField(value);
300 }
301 else if (name.equals(SORT_ORDER_PARAM)) {
302 if (value.equals(SORT_ORDER_DESCENDING)) {
303 this.solr_src.setSortOrder(SolrQueryWrapper.SORT_DESCENDING);
304 } else {
305 this.solr_src.setSortOrder(SolrQueryWrapper.SORT_ASCENDING);
306 }
307 }
308 else if (name.equals(LEVEL_PARAM))
309 {
310 if (value.toUpperCase().equals("SEC"))
311 {
312 index = "sidx";
313 }
314 else
315 {
316 index = "didx";
317 }
318 }
319 // Would facets ever come in through params???
320 else if (name.equals("facets") && value.length() > 0)
321 {
322 String[] facets = value.split(",");
323
324 for (String facet : facets)
325 {
326 this.solr_src.addFacet(facet);
327 }
328 }
329 else if (name.equals("facetQueries") && value.length() > 0)
330 {
331 this.solr_src.addFacetQuery(value);
332 }
333 else if (name.equals(INDEX_SUBCOLLECTION_PARAM))
334 {
335 physical_sub_index_name = value;
336 }
337 else if (name.equals(INDEX_LANGUAGE_PARAM))
338 {
339 physical_index_language_name = value;
340 } // ignore any others
341 }
342 // set up start and end results if necessary
343 int start_results = 0;
344 if (start_page != 1)
345 {
346 start_results = ((start_page - 1) * hits_per_page) ;
347 }
348 int end_results = hits_per_page * start_page;
349 this.solr_src.setStartResults(start_results);
350 this.solr_src.setEndResults(end_results);
351 this.solr_src.setMaxDocs(maxdocs);
352
353 if (index.equals("sidx") || index.equals("didx"))
354 {
355 if (physical_sub_index_name != null)
356 {
357 index += physical_sub_index_name;
358 }
359 if (physical_index_language_name != null)
360 {
361 index += physical_index_language_name;
362 }
363 }
364
365 // now we know the index level, we can dig out the required
366 // solr-core, (caching the result in 'solr_core_cache')
367 String core_name = getCollectionCoreNamePrefix() + "-" + index;
368
369 SolrServer solr_core = null;
370 //CHECK HERE
371 if (!solr_core_cache.containsKey(core_name))
372 {
373 solr_core = new HttpSolrServer(this.solr_servlet_base_url+"/"+core_name);
374 solr_core_cache.put(core_name, solr_core);
375 }
376 else
377 {
378 solr_core = solr_core_cache.get(core_name);
379 }
380
381 this.solr_src.setSolrCore(solr_core);
382 this.solr_src.setCollectionCoreNamePrefix(getCollectionCoreNamePrefix());
383 this.solr_src.initialise();
384 return true;
385 }
386
387 /** do the query */
388 protected Object runQuery(String query)
389 {
390 try
391 {
392 //if it is a Highlighting Query - execute it
393 this.solr_src.setHighlightField(indexField);
394 if(hldocOID != null)
395 {
396 String rslt = this.solr_src.runHighlightingQuery(query,hldocOID);
397 // Check result
398 if (rslt != null)
399 {
400 return rslt;
401 }
402 //Highlighting request failed. Do standard request.
403 hldocOID = null;
404 }
405 SharedSoleneQueryResult sqr = this.solr_src.runQuery(query);
406
407 return sqr;
408 }
409 catch (Exception e)
410 {
411 logger.error("Exception happened in run query: ", e);
412 }
413
414 return null;
415 }
416
417
418 /** get the total number of docs that match */
419 protected long numDocsMatched(Object query_result)
420 {
421 return ((SharedSoleneQueryResult) query_result).getTotalDocs();
422
423 }
424
425 /** get the list of doc ids */
426 protected String[] getDocIDs(Object query_result)
427 {
428 Vector docs = ((SharedSoleneQueryResult) query_result).getDocs();
429 String[] doc_nums = new String[docs.size()];
430 for (int d = 0; d < docs.size(); d++)
431 {
432 String doc_num = ((SharedSoleneQueryResult.DocInfo) docs.elementAt(d)).id_;
433 doc_nums[d] = doc_num;
434 }
435 return doc_nums;
436 }
437
438 /** get the list of doc ranks */
439 protected String[] getDocRanks(Object query_result)
440 {
441 Vector docs = ((SharedSoleneQueryResult) query_result).getDocs();
442 String[] doc_ranks = new String[docs.size()];
443 for (int d = 0; d < docs.size(); d++)
444 {
445 doc_ranks[d] = Float.toString(((SharedSoleneQueryResult.DocInfo) docs.elementAt(d)).rank_);
446 }
447 return doc_ranks;
448 }
449
450 /** add in term info if available */
451 protected boolean addTermInfo(Element term_list, HashMap params, Object query_result)
452 {
453 Document doc = term_list.getOwnerDocument();
454 String query_level = (String) params.get(LEVEL_PARAM); // the current query level
455
456 Vector terms = ((SharedSoleneQueryResult) query_result).getTerms();
457 for (int t = 0; t < terms.size(); t++)
458 {
459 SharedSoleneQueryResult.TermInfo term_info = (SharedSoleneQueryResult.TermInfo) terms.get(t);
460
461 Element term_elem = doc.createElement(GSXML.TERM_ELEM);
462 term_elem.setAttribute(GSXML.NAME_ATT, term_info.term_);
463 term_elem.setAttribute(FREQ_ATT, "" + term_info.term_freq_);
464 term_elem.setAttribute(NUM_DOCS_MATCH_ATT, "" + term_info.match_docs_);
465 term_elem.setAttribute(FIELD_ATT, term_info.field_);
466 term_list.appendChild(term_elem);
467 }
468
469 Vector stopwords = ((SharedSoleneQueryResult) query_result).getStopWords();
470 for (int t = 0; t < stopwords.size(); t++)
471 {
472 String stopword = (String) stopwords.get(t);
473
474 Element stopword_elem = doc.createElement(GSXML.STOPWORD_ELEM);
475 stopword_elem.setAttribute(GSXML.NAME_ATT, stopword);
476 term_list.appendChild(stopword_elem);
477 }
478
479 return true;
480 }
481
482 protected ArrayList<FacetWrapper> getFacets(Object query_result, String lang)
483 {
484 if (!(query_result instanceof SolrQueryResult))
485 {
486 return null;
487 }
488
489 SolrQueryResult result = (SolrQueryResult) query_result;
490 List<FacetField> facets = result.getFacetResults();
491
492 if (facets == null)
493 {
494 return null;
495 }
496
497 ArrayList<FacetWrapper> newFacetList = new ArrayList<FacetWrapper>();
498
499 for (FacetField facet : facets)
500 {
501 SolrFacetWrapper wrap = new SolrFacetWrapper(facet);
502 String fname = wrap.getName();
503 String dname = getDisplayText(_facet_display_names.get(fname), GSXML.DISPLAY_TEXT_NAME, lang, "en", "metadata_names");
504 wrap.setDisplayName(dname);
505 newFacetList.add(wrap);
506 }
507
508 return newFacetList;
509 }
510 @Override
511 protected Map<String, Map<String, List<String>>> getHighlightSnippets(Object query_result)
512 {
513 if (!(query_result instanceof SolrQueryResult))
514 {
515 return null;
516 }
517
518 SolrQueryResult result = (SolrQueryResult) query_result;
519
520 return result.getHighlightResults();
521 }
522
523
524 protected String getCollectionCoreNamePrefix() {
525 String site_name = this.router.getSiteName();
526 String coll_name = this.cluster_name;
527 String collection_core_name_prefix = site_name + "-" + coll_name;
528 return collection_core_name_prefix;
529 }
530
531 private boolean loadSolrCores() {
532
533 HttpSolrServer solrServer = new HttpSolrServer(solr_servlet_base_url);
534 // Max retries
535 solrServer.setMaxRetries(1);
536 // Connection Timeout
537 solrServer.setConnectionTimeout(3000);
538 //Cores
539 String coreSecName = getCollectionCoreNamePrefix() + "-sidx";
540 String coreDocName = getCollectionCoreNamePrefix() + "-didx";
541
542
543 if (!checkSolrCore(coreSecName, solrServer)){
544 if (!activateSolrCore(coreSecName, solrServer)){
545 logger.error("Couldn't activate Solr core " + coreSecName + " for collection " + cluster_name);
546 return false;
547 }
548 }
549 if (!checkSolrCore(coreDocName, solrServer)){
550 if (!activateSolrCore(coreDocName, solrServer)){
551 logger.error("Couldn't activate Solr core " + coreDocName + " for collection " + cluster_name);
552 return false;
553 }
554 }
555 return true;
556 }
557
558 private boolean checkSolrCore(String coreName, HttpSolrServer solrServer) {
559 CoreAdminRequest adminRequest = new CoreAdminRequest();
560 adminRequest.setAction(CoreAdminAction.STATUS);
561 adminRequest.setCoreName(coreName);
562
563 try {
564 CoreAdminResponse adminResponse = adminRequest.process(solrServer);
565 NamedList<NamedList<Object>> coreStatus = adminResponse.getCoreStatus();
566 NamedList<Object> coreList = coreStatus.getVal(0);
567 if (coreList != null) {
568 if (coreList.get("name") == null) {
569 logger.warn("Solr core " + coreName + " for collection " + cluster_name + " not exists.");
570 return false;
571 }
572 }
573
574 } catch (SolrServerException e) {
575 e.printStackTrace();
576 return false;
577 } catch (IOException e) {
578 e.printStackTrace();
579 return false;
580 } catch (RemoteSolrException e1){
581 logger.error("Check solr core " + coreName + " for collection " + cluster_name + " failed.");
582 e1.printStackTrace();
583 return false;
584 }
585 return true;
586 }
587
588 private boolean activateSolrCore(String coreName, HttpSolrServer solrServer) {
589 String dataDir = GSFile.collectionIndexDir(site_home, cluster_name) + File.separator + coreName.substring(coreName.length() - 4);
590 String instanceDir = GSFile.collectionEtcDir(site_home, cluster_name);
591
592 try {
593 CoreAdminRequest.createCore(coreName, instanceDir, solrServer, "", "", dataDir, "");
594 logger.warn("Solr core " + coreName + " for collection " + cluster_name + " activated.");
595 } catch (SolrServerException e1) {
596 e1.printStackTrace();
597 return false;
598 } catch (IOException e1) {
599 e1.printStackTrace();
600 return false;
601 } catch (RemoteSolrException e1){
602 logger.error("Activation solr core " + coreName + " for collection " + cluster_name + " failed.");
603 e1.printStackTrace();
604 return false;
605 }
606
607 return true;
608 }
609
610}
Note: See TracBrowser for help on using the repository browser.