source: trunk/gsdl/src/java/org/nzdl/gsdl/LuceneWrap/GS2LuceneQuery.java@ 13570

Last change on this file since 13570 was 13570, checked in by kjdon, 17 years ago

catch unforseen exceptions, and check for null sort_field and start_results<1

  • Property svn:keywords set to Author Date Id Revision
File size: 19.3 KB
Line 
1/**********************************************************************
2 *
3 * GS2LuceneQuery.java
4 *
5 * Copyright 2004 The New Zealand Digital Library Project
6 *
7 * A component of the Greenstone digital library software
8 * from the New Zealand Digital Library Project at the
9 * University of Waikato, New Zealand.
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 *
25 *********************************************************************/
26package org.nzdl.gsdl.LuceneWrap;
27
28
29import java.io.*;
30import java.util.*;
31import java.util.regex.*;
32
33import org.apache.lucene.analysis.Analyzer;
34import org.apache.lucene.analysis.standard.StandardAnalyzer;
35import org.apache.lucene.document.Document;
36import org.apache.lucene.index.IndexReader;
37import org.apache.lucene.index.Term;
38import org.apache.lucene.index.TermDocs;
39import org.apache.lucene.queryParser.ParseException;
40import org.apache.lucene.queryParser.QueryParser;
41import org.apache.lucene.search.BooleanQuery.TooManyClauses;
42import org.apache.lucene.search.Filter;
43import org.apache.lucene.search.Hit;
44import org.apache.lucene.search.Hits;
45import org.apache.lucene.search.IndexSearcher;
46import org.apache.lucene.search.Query;
47import org.apache.lucene.search.RangeFilter;
48import org.apache.lucene.search.Searcher;
49import org.apache.lucene.search.ScoreDoc;
50import org.apache.lucene.search.Sort;
51import org.apache.lucene.search.TopFieldDocs;
52
53
54public class GS2LuceneQuery
55{
56
57
58 static private String TEXTFIELD = "TX";
59
60 // Use the standard set of English stop words by default
61 static private String[] stop_words = StandardAnalyzer.STOP_WORDS;
62
63 private String full_indexdir="";
64 private String default_conjunction_operator = "OR";
65 private String fuzziness = null;
66 private String sort_field = null;
67 private Sort sorter=new Sort();
68 private String filter_string = null;
69 private Filter filter = null;
70 private int start_results=1;
71 private int end_results=Integer.MAX_VALUE;
72
73 private QueryParser query_parser = null;
74 private QueryParser query_parser_no_stop_words = null;
75 private Searcher searcher = null;
76 private IndexReader reader = null;
77
78 public GS2LuceneQuery() {
79
80 // Create one query parser with the standard set of stop words, and one with none
81
82 query_parser = new QueryParser(TEXTFIELD, new StandardAnalyzer(stop_words));
83 query_parser_no_stop_words = new QueryParser(TEXTFIELD, new StandardAnalyzer(new String[] { }));
84 }
85
86
87 public boolean initialise() {
88
89 if (full_indexdir==null || full_indexdir.length()==-1){
90 System.out.println("Index directory is not indicated ");
91 return false;
92 }
93 try {
94 searcher = new IndexSearcher(full_indexdir);
95 reader = ((IndexSearcher) searcher).getIndexReader();
96
97 }
98 catch (IOException exception) {
99 exception.printStackTrace();
100 return false;
101 }
102 return true;
103
104 }
105
106 public LuceneQueryResult runQuery(String query_string) {
107
108 if (query_string == null || query_string.equals("")) {
109 System.out.println("The query word is not indicated ");
110 return null;
111 }
112
113 LuceneQueryResult lucene_query_result=new LuceneQueryResult();
114 lucene_query_result.clear();
115
116 try {
117 Query query_including_stop_words = query_parser_no_stop_words.parse(query_string);
118 query_including_stop_words = query_including_stop_words.rewrite(reader);
119
120 Query query = parseQuery(reader, query_parser, query_string, fuzziness);
121 query = query.rewrite(reader);
122
123 // Get the list of expanded query terms and their frequencies
124 // num docs matching, and total frequency
125 HashSet terms = new HashSet();
126 query.extractTerms(terms);
127
128 Iterator iter = terms.iterator();
129 while (iter.hasNext()) {
130
131 Term term = (Term) iter.next();
132
133 // Get the term frequency over all the documents
134 TermDocs term_docs = reader.termDocs(term);
135 int term_freq = term_docs.freq();
136 int match_docs = 0;
137 if (term_freq != 0) match_docs++;
138 while (term_docs.next()) {
139 term_freq += term_docs.freq();
140 if (term_docs.freq()!= 0) {
141 match_docs++;
142 }
143 }
144
145 // Create a term
146 lucene_query_result.addTerm(term.text(), term.field(), match_docs, term_freq);
147 }
148
149 // Get the list of stop words removed from the query
150 HashSet terms_including_stop_words = new HashSet();
151 query_including_stop_words.extractTerms(terms_including_stop_words);
152 Iterator terms_including_stop_words_iter = terms_including_stop_words.iterator();
153 while (terms_including_stop_words_iter.hasNext()) {
154 Term term = (Term) terms_including_stop_words_iter.next();
155 if (!terms.contains(term)) {
156 lucene_query_result.addStopWord(term.text());
157 }
158 }
159
160 // do the query
161 // Simple case for getting all the matching documents
162 if (end_results == Integer.MAX_VALUE) {
163 // Perform the query (filter and sorter may be null)
164 Hits hits = searcher.search(query, filter, sorter);
165 lucene_query_result.setTotalDocs(hits.length());
166
167 // Output the matching documents
168 lucene_query_result.setStartResults(start_results);
169 lucene_query_result.setEndResults(hits.length());
170
171 for (int i = start_results; i <= hits.length(); i++) {
172 Document doc = hits.doc(i - 1);
173 lucene_query_result.addDoc(Long.parseLong(doc.get("nodeID").trim()), hits.score(i-1));
174 }
175 }
176
177 // Slightly more complicated case for returning a subset of the matching documents
178 else {
179 // Perform the query (filter may be null)
180 TopFieldDocs hits = searcher.search(query, filter, end_results, sorter);
181 lucene_query_result.setTotalDocs(hits.totalHits);
182
183 lucene_query_result.setStartResults(start_results);
184 lucene_query_result.setEndResults(end_results < hits.scoreDocs.length ? end_results: hits.scoreDocs.length);
185
186 // Output the matching documents
187 for (int i = start_results; (i <= hits.scoreDocs.length && i <= end_results); i++) {
188 Document doc = reader.document(hits.scoreDocs[i - 1].doc);
189 lucene_query_result.addDoc(Long.parseLong(doc.get("nodeID").trim()), hits.scoreDocs[i-1].score);
190 }
191 }
192 }
193
194 catch (ParseException parse_exception) {
195 lucene_query_result.setError(LuceneQueryResult.PARSE_ERROR);
196 }
197 catch (TooManyClauses too_many_clauses_exception) {
198 lucene_query_result.setError(LuceneQueryResult.TOO_MANY_CLAUSES_ERROR);
199 }
200 catch (IOException exception) {
201 lucene_query_result.setError(LuceneQueryResult.IO_ERROR);
202 exception.printStackTrace();
203 }
204 catch (Exception exception) {
205 lucene_query_result.setError(LuceneQueryResult.OTHER_ERROR);
206 exception.printStackTrace();
207 }
208 return lucene_query_result;
209 }
210
211 public void setDefaultConjunctionOperator(String default_conjunction_operator) {
212 this.default_conjunction_operator = default_conjunction_operator.toUpperCase();
213 if (default_conjunction_operator == "AND") {
214 query_parser.setDefaultOperator(query_parser.AND_OPERATOR);
215 query_parser_no_stop_words.setDefaultOperator(query_parser.AND_OPERATOR);
216 } else { // default is OR
217 query_parser.setDefaultOperator(query_parser.OR_OPERATOR);
218 query_parser_no_stop_words.setDefaultOperator(query_parser.OR_OPERATOR);
219 }
220 }
221
222 public String getDefaultConjunctionOperator() {
223 return this.default_conjunction_operator;
224 }
225
226 public void setEndResults(int end_results) {
227 this.end_results = end_results;
228 }
229 public int getEndResults() {
230 return this.end_results;
231 }
232
233 public void setFilterString(String filter_string) {
234 this.filter_string = filter_string;
235 this.filter = parseFilterString(filter_string);
236 }
237 public String getFilterString() {
238 return this.filter_string ;
239 }
240
241 public Filter getFilter() {
242 return this.filter;
243 }
244
245 public void setIndexDir(String full_indexdir) {
246 this.full_indexdir = full_indexdir;
247 }
248
249 public void setFuzziness(String fuzziness) {
250 this.fuzziness = fuzziness;
251 }
252 public String getFuzziness() {
253 return this.fuzziness;
254 }
255
256 public void setSortField(String sort_field) {
257 this.sort_field = sort_field;
258 if (sort_field == null) {
259 this.sorter = new Sort();
260 } else {
261 this.sorter = new Sort(sort_field);
262 }
263 }
264 public String getSortField() {
265 return this.sort_field;
266 }
267
268 public void setStartResults(int start_results) {
269 if (start_results < 1) {
270 start_results = 1;
271 }
272 this.start_results = start_results;
273 }
274 public int getStartResults() {
275 return this.start_results;
276 }
277
278 public void cleanUp() {
279 try {
280 searcher.close();
281 } catch (IOException exception) {
282 exception.printStackTrace();
283 }
284 }
285
286 private Query parseQuery(IndexReader reader, QueryParser query_parser, String query_string, String fuzziness)
287 throws java.io.IOException, org.apache.lucene.queryParser.ParseException
288 {
289 // Split query string into the search terms and the filter terms
290 // * The first +(...) term contains the search terms so count
291 // up '(' and stop when we finish matching ')'
292 int offset = 0;
293 int paren_count = 0;
294 boolean seen_paren = false;
295 while (offset < query_string.length() && (!seen_paren || paren_count > 0)) {
296 if (query_string.charAt(offset) == '(') {
297 paren_count++;
298 seen_paren = true;
299 }
300 if (query_string.charAt(offset) == ')') {
301 paren_count--;
302 }
303 offset++;
304 }
305 String query_prefix = query_string.substring(0, offset);
306 String query_suffix = query_string.substring(offset);
307
308 ///ystem.err.println("Prefix: " + query_prefix);
309 ///ystem.err.println("Suffix: " + query_suffix);
310
311 Query query = query_parser.parse(query_prefix);
312 query = query.rewrite(reader);
313
314 // If this is a fuzzy search, then we need to add the fuzzy
315 // flag to each of the query terms
316 if (fuzziness != null && query.toString().length() > 0) {
317
318 // Revert the query to a string
319 System.err.println("Rewritten query: " + query.toString());
320 // Search through the string for TX:<term> query terms
321 // and append the ~ operator. Note that this search will
322 // not change phrase searches (TX:"<term> <term>") as
323 // fuzzy searching is not possible for these entries.
324 // Yahoo! Time for a state machine!
325 StringBuffer mutable_query_string = new StringBuffer(query.toString());
326 int o = 0; // Offset
327 // 0 = BASE, 1 = SEEN_T, 2 = SEEN_TX, 3 = SEEN_TX:
328 int s = 0; // State
329 while(o < mutable_query_string.length()) {
330 char c = mutable_query_string.charAt(o);
331 if (s == 0 && c == TEXTFIELD.charAt(0)) {
332 ///ystem.err.println("Found T!");
333 s = 1;
334 }
335 else if (s == 1) {
336 if (c == TEXTFIELD.charAt(1)) {
337 ///ystem.err.println("Found X!");
338 s = 2;
339 }
340 else {
341 s = 0; // Reset
342 }
343 }
344 else if (s == 2) {
345 if (c == ':') {
346 ///ystem.err.println("Found TX:!");
347 s = 3;
348 }
349 else {
350 s = 0; // Reset
351 }
352 }
353 else if (s == 3) {
354 // Don't process phrases
355 if (c == '"') {
356 ///ystem.err.println("Stupid phrase...");
357 s = 0; // Reset
358 }
359 // Found the end of the term... add the
360 // fuzzy search indicator
361 // Nor outside the scope of parentheses
362 else if (Character.isWhitespace(c) || c == ')') {
363 ///ystem.err.println("Yahoo! Found fuzzy term.");
364 mutable_query_string.insert(o, '~' + fuzziness);
365 o++;
366 s = 0; // Reset
367 }
368 }
369 o++;
370 }
371 // If we were in the state of looking for the end of a
372 // term - then we just found it!
373 if (s == 3) {
374
375 mutable_query_string.append('~' + fuzziness);
376 }
377 // Reparse the query
378 ///ystem.err.println("Fuzzy query: " + mutable_query_string.toString() + query_suffix);
379 query = query_parser.parse(mutable_query_string.toString() + query_suffix);
380 }
381 else {
382 query = query_parser.parse(query_prefix + query_suffix);
383 }
384
385 return query;
386 }
387
388 private Filter parseFilterString(String filter_string)
389 {
390 Filter result = null;
391 Pattern pattern = Pattern.compile("\\s*\\+(\\w+)\\:([\\{\\[])(\\d+)\\s+TO\\s+(\\d+)([\\}\\]])\\s*");
392 Matcher matcher = pattern.matcher(filter_string);
393 if (matcher.matches()) {
394 String field_name = matcher.group(1);
395 boolean include_lower = matcher.group(2).equals("[");
396 String lower_term = matcher.group(3);
397 String upper_term = matcher.group(4);
398 boolean include_upper = matcher.group(5).equals("]");
399 result = new RangeFilter(field_name, lower_term, upper_term, include_lower, include_upper);
400 }
401 else {
402 System.err.println("Error: Could not understand filter string \"" + filter_string + "\"");
403 }
404 return result;
405 }
406
407
408 /** command line program and auxiliary methods */
409
410 // Fairly self-explanatory I should hope
411 static private boolean query_result_caching_enabled = false;
412
413 static public void main (String args[])
414 {
415 if (args.length == 0) {
416 System.out.println("Usage: GS2LuceneQuery <index directory> [-fuzziness value] [-filter filter_string] [-sort sort_field] [-dco AND|OR] [-startresults number -endresults number] [query]");
417 return;
418 }
419
420 try {
421 String index_directory = args[0];
422
423 GS2LuceneQuery queryer = new GS2LuceneQuery();
424 queryer.setIndexDir(index_directory);
425
426 // Prepare the index cache directory, if query result caching is enabled
427 if (query_result_caching_enabled) {
428 // Make the index cache directory if it doesn't already exist
429 File index_cache_directory = new File(index_directory, "cache");
430 if (!index_cache_directory.exists()) {
431 index_cache_directory.mkdir();
432 }
433
434 // Disable caching if the index cache directory isn't available
435 if (!index_cache_directory.exists() || !index_cache_directory.isDirectory()) {
436 query_result_caching_enabled = false;
437 }
438 }
439
440 String query_string = null;
441
442 // Parse the command-line arguments
443 for (int i = 1; i < args.length; i++) {
444 if (args[i].equals("-sort")) {
445 i++;
446 queryer.setSortField(args[i]);
447 }
448 else if (args[i].equals("-filter")) {
449 i++;
450 queryer.setFilterString(args[i]);
451 }
452 else if (args[i].equals("-dco")) {
453 i++;
454 queryer.setDefaultConjunctionOperator(args[i]);
455 }
456 else if (args[i].equals("-fuzziness")) {
457 i++;
458 queryer.setFuzziness(args[i]);
459 }
460 else if (args[i].equals("-startresults")) {
461 i++;
462 if (args[i].matches("\\d+")) {
463 queryer.setStartResults(Integer.parseInt(args[i]));
464 }
465 }
466 else if (args[i].equals("-endresults")) {
467 i++;
468 if (args[i].matches("\\d+")) {
469 queryer.setEndResults(Integer.parseInt(args[i]));
470 }
471 }
472 else {
473 query_string = args[i];
474 }
475 }
476
477 if (!queryer.initialise()) {
478 return;
479 }
480
481 // The query string has been specified as a command-line argument
482 if (query_string != null) {
483 runQueryCaching(index_directory, queryer, query_string);
484 }
485
486 // Read queries from STDIN
487 else {
488 BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
489 while (true) {
490 // Read the query from STDIN
491 query_string = in.readLine();
492 if (query_string == null || query_string.length() == -1) {
493 break;
494 }
495 runQueryCaching(index_directory, queryer, query_string);
496
497 }
498 }
499 queryer.cleanUp();
500 }
501 catch (IOException exception) {
502 exception.printStackTrace();
503 }
504 }
505
506 private static void runQueryCaching(String index_directory, GS2LuceneQuery queryer, String query_string)
507 throws IOException
508 {
509 StringBuffer query_results_xml = new StringBuffer();
510
511 // Check if this query result has been cached from a previous search (if it's enabled)
512 File query_result_cache_file = null;
513 if (query_result_caching_enabled) {
514 // Generate the cache file name from the query options
515 String query_result_cache_file_name = query_string + "-";
516 String fuzziness = queryer.getFuzziness();
517 query_result_cache_file_name += ((fuzziness != null) ? fuzziness : "") + "-";
518 String filter_string = queryer.getFilterString();
519 query_result_cache_file_name += ((filter_string != null) ? filter_string : "") + "-";
520 String sort_string = queryer.getSortField();
521 query_result_cache_file_name += ((sort_string != null) ? sort_string : "") + "-";
522 String default_conjunction_operator = queryer.getDefaultConjunctionOperator();
523 query_result_cache_file_name += default_conjunction_operator + "-";
524 int start_results = queryer.getStartResults();
525 int end_results = queryer.getEndResults();
526 query_result_cache_file_name += start_results + "-" + end_results;
527 query_result_cache_file_name = fileSafe(query_result_cache_file_name);
528
529 // If the query result cache file exists, just return its contents and we're done
530 File index_cache_directory = new File(index_directory, "cache");
531 query_result_cache_file = new File(index_cache_directory, query_result_cache_file_name);
532 if (query_result_cache_file.exists() && query_result_cache_file.isFile()) {
533 FileInputStream fis = new FileInputStream(query_result_cache_file);
534 InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
535 BufferedReader buffered_reader = new BufferedReader(isr);
536 String line = "";
537 while ((line = buffered_reader.readLine()) != null) {
538 query_results_xml.append(line + "\n");
539 }
540 String query_results_xml_string = query_results_xml.toString();
541 query_results_xml_string = query_results_xml_string.replaceFirst("cached=\"false\"", "cached=\"true\"");
542 System.out.print(query_results_xml_string);
543 return;
544 }
545 }
546
547 // not cached
548 query_results_xml.append("<ResultSet cached=\"false\">\n");
549 query_results_xml.append("<QueryString>" + LuceneQueryResult.xmlSafe(query_string) + "</QueryString>\n");
550 Filter filter = queryer.getFilter();
551 if (filter != null) {
552 query_results_xml.append("<FilterString>" + filter.toString() + "</FilterString>\n");
553 }
554
555 LuceneQueryResult query_result = queryer.runQuery(query_string);
556 if (query_result == null) {
557 System.err.println("Couldn't run the query");
558 return;
559 }
560
561 if (query_result.getError() != LuceneQueryResult.NO_ERROR) {
562 query_results_xml.append("<Error type=\""+query_result.getErrorString()+"\" />\n");
563 } else {
564 query_results_xml.append(query_result.getXMLString());
565 }
566 query_results_xml.append("</ResultSet>\n");
567
568 System.out.print(query_results_xml);
569
570 // Cache this query result, if desired
571 if (query_result_caching_enabled) {
572 FileWriter query_result_cache_file_writer = new FileWriter(query_result_cache_file);
573 query_result_cache_file_writer.write(query_results_xml.toString());
574 query_result_cache_file_writer.close();
575 }
576 }
577
578 private static String fileSafe(String text)
579 {
580 StringBuffer file_safe_text = new StringBuffer();
581 for (int i = 0; i < text.length(); i++) {
582 char character = text.charAt(i);
583 if ((character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') || character == '-') {
584 file_safe_text.append(character);
585 }
586 else {
587 file_safe_text.append('%');
588 file_safe_text.append((int) character);
589 }
590 }
591 return file_safe_text.toString();
592 }
593
594
595}
596
597
Note: See TracBrowser for help on using the repository browser.