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

Last change on this file since 28967 was 28967, checked in by kjdon, 10 years ago

no longer have this.doc to use. Need to create new Documents when needed

  • Property svn:executable set to *
File size: 15.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
21// Greenstone classes
22import java.io.File;
23import java.util.ArrayList;
24import java.util.Collection;
25import java.util.HashMap;
26import java.util.Iterator;
27import java.util.List;
28import java.util.Map;
29import java.util.Set;
30import java.util.Vector;
31
32import org.apache.log4j.Logger;
33import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
34import org.apache.solr.client.solrj.response.FacetField;
35import org.apache.solr.core.CoreContainer;
36import org.apache.solr.core.SolrCore;
37import org.greenstone.LuceneWrapper3.SharedSoleneQueryResult;
38import org.greenstone.gsdl3.util.FacetWrapper;
39import org.greenstone.gsdl3.util.GSFile;
40import org.greenstone.gsdl3.util.GSXML;
41import org.greenstone.gsdl3.util.SolrFacetWrapper;
42import org.greenstone.gsdl3.util.SolrQueryResult;
43import org.greenstone.gsdl3.util.SolrQueryWrapper;
44import org.greenstone.util.GlobalProperties;
45import org.w3c.dom.Document;
46import org.w3c.dom.Element;
47import org.w3c.dom.NodeList;
48
49public class GS2SolrSearch extends SharedSoleneGS2FieldSearch
50{
51 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.service.GS2SolrSearch.class.getName());
52
53 static protected CoreContainer all_solr_cores = null;
54
55 protected HashMap solr_core_cache;
56 protected SolrQueryWrapper solr_src = null;
57
58 protected ArrayList<String> _facets = new ArrayList<String>();
59
60 public GS2SolrSearch()
61 {
62 does_faceting = true;
63 // Used to store the solr cores that match the required 'level'
64 // of search (e.g. either document-level=>didx, or
65 // section-level=>sidx. The hashmap is filled out on demand
66 // based on 'level' parameter passed in to 'setUpQueryer()'
67
68 solr_core_cache = new HashMap();
69
70 if (all_solr_cores == null)
71 {
72 // Share one CoreContainer across all sites/collections
73 try
74 {
75 String gsdl3_writablehome = GlobalProperties.getGSDL3WritableHome();
76 String solr_ext_name = GlobalProperties.getProperty("gsdlext.solr.dirname", "solr");
77
78 String solr_home_str = GSFile.extHome(gsdl3_writablehome, solr_ext_name);
79
80 all_solr_cores = new CoreContainer(solr_home_str);
81 }
82 catch (Exception e)
83 {
84 e.printStackTrace();
85 }
86 }
87
88 this.solr_src = new SolrQueryWrapper();
89 }
90
91 /** configure this service */
92 public boolean configure(Element info, Element extra_info)
93 {
94 boolean success = super.configure(info, extra_info);
95
96 // 1. Make the CoreContainer reload solr.xml
97 // This is particularly needed for when activate.pl is executed during
98 // a running GS3 server. At that point, the solr collection is reactivated and
99 // we need to tell Greenstone that the solr index has changed. This requires
100 // the CoreContainer to reload the solr.xml file, and it all works again.
101
102 solr_core_cache.clear(); // clear the map of solr cores for this collection added to the map upon querying
103
104 // Reload the updated solr.xml into the CoreContainer
105 // (Doing an all_solr_cores.shutdown() first doesn't seem to be required)
106 try {
107 String solr_home_str = all_solr_cores.getSolrHome();
108 File solr_home = new File(solr_home_str);
109 File solr_xml = new File( solr_home,"solr.xml" );
110
111 all_solr_cores.load(solr_home_str,solr_xml);
112
113 } catch (Exception e) {
114 logger.error("Exception in GS2SolrSearch.configure(): " + e.getMessage());
115 e.printStackTrace();
116 return false;
117 }
118
119 if(!success) {
120 return false;
121 }
122
123 // 2. Setting up facets
124 // TODO - get these from build config, in case some haven't built
125 Element searchElem = (Element) GSXML.getChildByTagName(extra_info, GSXML.SEARCH_ELEM);
126 NodeList facet_list = info.getElementsByTagName("facet");
127 for (int i=0; i<facet_list.getLength(); i++) {
128 _facets.add(((Element)facet_list.item(i)).getAttribute(GSXML.SHORTNAME_ATT));
129 }
130 // NodeList configIndexElems = searchElem.getElementsByTagName(GSXML.INDEX_ELEM);
131
132 // ArrayList<String> chosenFacets = new ArrayList<String>();
133 // for (int i = 0; i < configIndexElems.getLength(); i++)
134 // {
135 // Element current = (Element) configIndexElems.item(i);
136 // if (current.getAttribute(GSXML.FACET_ATT).equals("true"))
137 // {
138 // chosenFacets.add(current.getAttribute(GSXML.NAME_ATT));
139 // }
140 // }
141
142 // Element indexListElem = (Element) GSXML.getChildByTagName(info, GSXML.INDEX_ELEM + GSXML.LIST_MODIFIER);
143 // NodeList buildIndexElems = indexListElem.getElementsByTagName(GSXML.INDEX_ELEM);
144
145 // for (int j = 0; j < buildIndexElems.getLength(); j++)
146 // {
147 // Element current = (Element) buildIndexElems.item(j);
148 // for (int i = 0; i < chosenFacets.size(); i++)
149 // {
150 // if (current.getAttribute(GSXML.NAME_ATT).equals(chosenFacets.get(i)))
151 // {
152 // _facets.add(current.getAttribute(GSXML.SHORTNAME_ATT));
153 // }
154 // }
155 // }
156
157 return true;
158 }
159
160 public void cleanUp()
161 {
162 super.cleanUp();
163 this.solr_src.cleanUp();
164
165 // When cleaning up, not only do we need to empty the solr_core_cache map, but we also need to remove all
166 // references to this collection's sorlcores in the CoreContainer object, which can be more SolrCores than
167 // the EmbeddedSolrServers instantiated and added to the solr_core_cache, since the cache does lazy loading
168 // while the CoreContainer contains all the cores defined in solr.xml, which includes all *possible* cores
169 // for this collection even if EmbeddedSolrServers for these were not added to the solr_core_cache_map.
170
171 // 1. clear the map keeping track of the solrcores' EmbeddedSolrServers in this collection
172 solr_core_cache.clear();
173
174 // 2. Remove all SolrCores in the CoreContainer (all_solr_cores) that are specific to this collection
175 String collection_core_name_prefix = getCollectionCoreNamePrefix();
176
177 if (all_solr_cores!=null) {
178 Collection<String> coreNames = all_solr_cores.getCoreNames();
179 if(!coreNames.isEmpty()) {
180 Iterator<String> coreIterator = coreNames.iterator();
181 while(coreIterator.hasNext()) {
182
183 String solrCoreName = coreIterator.next();
184 if(solrCoreName.startsWith(collection_core_name_prefix)) {
185
186 logger.error("**** Removing collection-specific core: " + solrCoreName + " from CoreContainer");
187
188 // CoreContainer.remove(String name): removes and returns registered core w/o decrementing it's reference count
189 // http://lucene.apache.org/solr/api/index.html?org/apache/solr/core/CoreContainer.html
190 SolrCore solr_core = all_solr_cores.remove(solrCoreName);
191 while(!solr_core.isClosed()) {
192 logger.error("@@@@@@ " + solrCoreName + " was not closed. Closing....");
193 solr_core.close(); // http://lucene.apache.org/solr/api/org/apache/solr/core/SolrCore.html
194 }
195 if(solr_core.isClosed()) {
196 logger.error("@@@@@@ " + solrCoreName + " is closed.");
197 }
198 solr_core = null;
199 }
200 }
201 }
202 }
203
204 // 3. if there are no more solr cores in Greenstone, then all_solr_cores will be empty, null the CoreContainer
205 // All going well, this will happen when we're ant stopping the Greenstone server and the last Solr collection
206 // is being deactivated
207 if (all_solr_cores!=null) {
208 Collection<String> coreNamesRemaining = all_solr_cores.getCoreNames();
209 if(coreNamesRemaining.isEmpty()) {
210 logger.error("**** CoreContainer contains 0 solrCores. Shutting down...");
211
212 all_solr_cores.shutdown(); // wouldn't do anything anyway for 0 cores I think
213 all_solr_cores = null;
214 }
215 else { // else part is just for debugging
216 Iterator coreIterator = coreNamesRemaining.iterator();
217 while(coreIterator.hasNext()) {
218 logger.error("**** Core: " + coreIterator.next() + " still exists in CoreContainer");
219 }
220 }
221 }
222 }
223
224 /** methods to handle actually doing the query */
225
226 /** do any initialisation of the query object */
227 protected boolean setUpQueryer(HashMap params)
228 {
229 this.solr_src.clearFacets();
230 this.solr_src.clearFacetQueries();
231
232 for (int i = 0; i < _facets.size(); i++)
233 {
234 this.solr_src.addFacet(_facets.get(i));
235 }
236
237 String index = "didx";
238 String physical_index_language_name = null;
239 String physical_sub_index_name = null;
240 int maxdocs = 100;
241 int hits_per_page = 20;
242 int start_page = 1;
243 // set up the query params
244 Set entries = params.entrySet();
245 Iterator i = entries.iterator();
246 while (i.hasNext())
247 {
248 Map.Entry m = (Map.Entry) i.next();
249 String name = (String) m.getKey();
250 String value = (String) m.getValue();
251
252 if (name.equals(MAXDOCS_PARAM) && !value.equals(""))
253 {
254 maxdocs = Integer.parseInt(value);
255 }
256 else if (name.equals(HITS_PER_PAGE_PARAM))
257 {
258 hits_per_page = Integer.parseInt(value);
259 }
260 else if (name.equals(START_PAGE_PARAM))
261 {
262 start_page = Integer.parseInt(value);
263 }
264 else if (name.equals(MATCH_PARAM))
265 {
266 if (value.equals(MATCH_PARAM_ALL))
267 {
268 this.solr_src.setDefaultConjunctionOperator("AND");
269 }
270 else
271 {
272 this.solr_src.setDefaultConjunctionOperator("OR");
273 }
274 }
275 else if (name.equals(RANK_PARAM))
276 {
277 if (value.equals(RANK_PARAM_RANK))
278 {
279 value = SolrQueryWrapper.SORT_BY_RANK;
280 } else if (value.equals(RANK_PARAM_NONE)) {
281 value = SolrQueryWrapper.SORT_BY_INDEX_ORDER;
282 }
283
284 this.solr_src.setSortField(value);
285 }
286 else if (name.equals(SORT_ORDER_PARAM)) {
287 if (value.equals(SORT_ORDER_DESCENDING)) {
288 this.solr_src.setSortOrder(SolrQueryWrapper.SORT_DESCENDING);
289 } else {
290 this.solr_src.setSortOrder(SolrQueryWrapper.SORT_ASCENDING);
291 }
292 }
293 else if (name.equals(LEVEL_PARAM))
294 {
295 if (value.toUpperCase().equals("SEC"))
296 {
297 index = "sidx";
298 }
299 else
300 {
301 index = "didx";
302 }
303 }
304 // Would facets ever come in through params???
305 else if (name.equals("facets") && value.length() > 0)
306 {
307 String[] facets = value.split(",");
308
309 for (String facet : facets)
310 {
311 this.solr_src.addFacet(facet);
312 }
313 }
314 else if (name.equals("facetQueries") && value.length() > 0)
315 {
316 this.solr_src.addFacetQuery(value);
317 }
318 else if (name.equals(INDEX_SUBCOLLECTION_PARAM))
319 {
320 physical_sub_index_name = value;
321 }
322 else if (name.equals(INDEX_LANGUAGE_PARAM))
323 {
324 physical_index_language_name = value;
325 } // ignore any others
326 }
327 // set up start and end results if necessary
328 int start_results = 1;
329 if (start_page != 1)
330 {
331 start_results = ((start_page - 1) * hits_per_page) + 1;
332 }
333 int end_results = hits_per_page * start_page;
334 this.solr_src.setStartResults(start_results);
335 this.solr_src.setEndResults(end_results);
336 this.solr_src.setMaxDocs(maxdocs);
337
338 if (index.equals("sidx") || index.equals("didx"))
339 {
340 if (physical_sub_index_name != null)
341 {
342 index += physical_sub_index_name;
343 }
344 if (physical_index_language_name != null)
345 {
346 index += physical_index_language_name;
347 }
348 }
349
350 // now we know the index level, we can dig out the required
351 // solr-core, (caching the result in 'solr_core_cache')
352 String core_name = getCollectionCoreNamePrefix() + "-" + index;
353
354 EmbeddedSolrServer solr_core = null;
355
356 if (!solr_core_cache.containsKey(core_name))
357 {
358 solr_core = new EmbeddedSolrServer(all_solr_cores, core_name);
359
360 solr_core_cache.put(core_name, solr_core);
361 }
362 else
363 {
364 solr_core = (EmbeddedSolrServer) solr_core_cache.get(core_name);
365 }
366
367 this.solr_src.setSolrCore(solr_core);
368 this.solr_src.initialise();
369 return true;
370 }
371
372 /** do the query */
373 protected Object runQuery(String query)
374 {
375 try
376 {
377 //SharedSoleneQueryResult sqr = this.solr_src.runQuery(query);
378 SharedSoleneQueryResult sqr = this.solr_src.runQuery(query);
379
380 return sqr;
381 }
382 catch (Exception e)
383 {
384 logger.error("Exception happened in run query: ", e);
385 }
386
387 return null;
388 }
389
390 /** get the total number of docs that match */
391 protected long numDocsMatched(Object query_result)
392 {
393 return ((SharedSoleneQueryResult) query_result).getTotalDocs();
394
395 }
396
397 /** get the list of doc ids */
398 protected String[] getDocIDs(Object query_result)
399 {
400 Vector docs = ((SharedSoleneQueryResult) query_result).getDocs();
401 String[] doc_nums = new String[docs.size()];
402 for (int d = 0; d < docs.size(); d++)
403 {
404 String doc_num = ((SharedSoleneQueryResult.DocInfo) docs.elementAt(d)).id_;
405 doc_nums[d] = doc_num;
406 }
407 return doc_nums;
408 }
409
410 /** get the list of doc ranks */
411 protected String[] getDocRanks(Object query_result)
412 {
413 Vector docs = ((SharedSoleneQueryResult) query_result).getDocs();
414 String[] doc_ranks = new String[docs.size()];
415 for (int d = 0; d < docs.size(); d++)
416 {
417 doc_ranks[d] = Float.toString(((SharedSoleneQueryResult.DocInfo) docs.elementAt(d)).rank_);
418 }
419 return doc_ranks;
420 }
421
422 /** add in term info if available */
423 protected boolean addTermInfo(Element term_list, HashMap params, Object query_result)
424 {
425 Document doc = term_list.getOwnerDocument();
426 String query_level = (String) params.get(LEVEL_PARAM); // the current query level
427
428 Vector terms = ((SharedSoleneQueryResult) query_result).getTerms();
429 for (int t = 0; t < terms.size(); t++)
430 {
431 SharedSoleneQueryResult.TermInfo term_info = (SharedSoleneQueryResult.TermInfo) terms.get(t);
432
433 Element term_elem = doc.createElement(GSXML.TERM_ELEM);
434 term_elem.setAttribute(GSXML.NAME_ATT, term_info.term_);
435 term_elem.setAttribute(FREQ_ATT, "" + term_info.term_freq_);
436 term_elem.setAttribute(NUM_DOCS_MATCH_ATT, "" + term_info.match_docs_);
437 term_elem.setAttribute(FIELD_ATT, term_info.field_);
438 term_list.appendChild(term_elem);
439 }
440
441 Vector stopwords = ((SharedSoleneQueryResult) query_result).getStopWords();
442 for (int t = 0; t < stopwords.size(); t++)
443 {
444 String stopword = (String) stopwords.get(t);
445
446 Element stopword_elem = doc.createElement(GSXML.STOPWORD_ELEM);
447 stopword_elem.setAttribute(GSXML.NAME_ATT, stopword);
448 term_list.appendChild(stopword_elem);
449 }
450
451 return true;
452 }
453
454 protected ArrayList<FacetWrapper> getFacets(Object query_result)
455 {
456 if (!(query_result instanceof SolrQueryResult))
457 {
458 return null;
459 }
460
461 SolrQueryResult result = (SolrQueryResult) query_result;
462 List<FacetField> facets = result.getFacetResults();
463
464 if (facets == null)
465 {
466 return null;
467 }
468
469 ArrayList<FacetWrapper> newFacetList = new ArrayList<FacetWrapper>();
470
471 for (FacetField facet : facets)
472 {
473 SolrFacetWrapper wrap = new SolrFacetWrapper(facet);
474 // String name = wrap.getName();
475 // String display_name = "Poo";
476 // wrap.setDisplayName(display_name);
477
478 newFacetList.add(wrap);
479 }
480
481 return newFacetList;
482 }
483
484
485 protected String getCollectionCoreNamePrefix() {
486 String site_name = this.router.getSiteName();
487 String coll_name = this.cluster_name;
488 String collection_core_name_prefix = site_name + "-" + coll_name;
489 return collection_core_name_prefix;
490 }
491}
Note: See TracBrowser for help on using the repository browser.