pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / queryparser / src / java / org / apache / lucene / queryParser / standard / QueryParserWrapper.java
1 package org.apache.lucene.queryParser.standard;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import java.text.Collator;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Map;
25
26 import org.apache.lucene.analysis.Analyzer;
27 import org.apache.lucene.document.DateTools;
28 import org.apache.lucene.document.DateTools.Resolution;
29 import org.apache.lucene.queryParser.ParseException;
30 import org.apache.lucene.queryParser.QueryParser;
31 import org.apache.lucene.queryParser.core.QueryNodeException;
32 import org.apache.lucene.queryParser.core.config.FieldConfig;
33 import org.apache.lucene.queryParser.core.config.QueryConfigHandler;
34 import org.apache.lucene.queryParser.core.nodes.QueryNode;
35 import org.apache.lucene.queryParser.core.parser.SyntaxParser;
36 import org.apache.lucene.queryParser.core.processors.QueryNodeProcessor;
37 import org.apache.lucene.queryParser.standard.builders.StandardQueryBuilder;
38 import org.apache.lucene.queryParser.standard.builders.StandardQueryTreeBuilder;
39 import org.apache.lucene.queryParser.standard.config.StandardQueryConfigHandler;
40 import org.apache.lucene.queryParser.standard.config.StandardQueryConfigHandler.ConfigurationKeys;
41 import org.apache.lucene.queryParser.standard.parser.StandardSyntaxParser;
42 import org.apache.lucene.queryParser.standard.processors.StandardQueryNodeProcessorPipeline;
43 import org.apache.lucene.search.BooleanClause;
44 import org.apache.lucene.search.FuzzyQuery;
45 import org.apache.lucene.search.MultiTermQuery;
46 import org.apache.lucene.search.Query;
47
48 /**
49  * This class performs the query parsing using the new query parser
50  * implementation, but keeps the old {@link QueryParser} API. <br/>
51  * <br/>
52  * This class should be used when the new query parser features are and the old
53  * {@link QueryParser} API are needed at the same time. <br/>
54  * 
55  * @deprecated this class will be removed soon, it's a temporary class to be
56  *             used along the transition from the old query parser to the new
57  *             one
58  */
59 @Deprecated
60 public class QueryParserWrapper {
61
62   /**
63    * The default operator for parsing queries. Use
64    * {@link QueryParserWrapper#setDefaultOperator} to change it.
65    */
66   static public enum Operator { OR, AND }
67
68   // the nested class:
69   /** Alternative form of QueryParser.Operator.AND */
70   public static final Operator AND_OPERATOR = Operator.AND;
71
72   /** Alternative form of QueryParser.Operator.OR */
73   public static final Operator OR_OPERATOR = Operator.OR;
74
75   /**
76    * Returns a String where those characters that QueryParser expects to be
77    * escaped are escaped by a preceding <code>\</code>.
78    */
79   public static String escape(String s) {
80     StringBuilder sb = new StringBuilder();
81     for (int i = 0; i < s.length(); i++) {
82       char c = s.charAt(i);
83       // These characters are part of the query syntax and must be escaped
84       if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')'
85           || c == ':' || c == '^' || c == '[' || c == ']' || c == '\"'
86           || c == '{' || c == '}' || c == '~' || c == '*' || c == '?'
87           || c == '|' || c == '&') {
88         sb.append('\\');
89       }
90       sb.append(c);
91     }
92     return sb.toString();
93   }
94
95   private SyntaxParser syntaxParser = new StandardSyntaxParser();
96
97   private StandardQueryConfigHandler config;
98
99   private StandardQueryParser qpHelper;
100
101   private QueryNodeProcessor processorPipeline;
102
103   private StandardQueryBuilder builder = new StandardQueryTreeBuilder();
104
105   private String defaultField;
106
107   public QueryParserWrapper(String defaultField, Analyzer analyzer) {
108     this.defaultField = defaultField;
109
110     this.qpHelper = new StandardQueryParser();
111
112     this.config = (StandardQueryConfigHandler) qpHelper.getQueryConfigHandler();
113
114     this.qpHelper.setAnalyzer(analyzer);
115
116     this.processorPipeline = new StandardQueryNodeProcessorPipeline(this.config);
117
118   }
119
120   StandardQueryParser getQueryParserHelper() {
121     return qpHelper;
122   }
123
124   public String getField() {
125     return this.defaultField;
126   }
127
128   public Analyzer getAnalyzer() {
129
130     if (this.config != null) {
131       return this.config.get(ConfigurationKeys.ANALYZER);
132     }
133
134     return null;
135
136   }
137
138   /**
139    * Sets the {@link StandardQueryBuilder} used to generate a {@link Query}
140    * object from the parsed and processed query node tree.
141    * 
142    * @param builder the builder
143    */
144   public void setQueryBuilder(StandardQueryBuilder builder) {
145     this.builder = builder;
146   }
147
148   /**
149    * Sets the {@link QueryNodeProcessor} used to process the query node tree
150    * generated by the
151    * {@link org.apache.lucene.queryParser.standard.parser.StandardSyntaxParser}.
152    * 
153    * @param processor the processor
154    */
155   public void setQueryProcessor(QueryNodeProcessor processor) {
156     this.processorPipeline = processor;
157     this.processorPipeline.setQueryConfigHandler(this.config);
158
159   }
160
161   /**
162    * Sets the {@link QueryConfigHandler} used by the {@link QueryNodeProcessor}
163    * set to this object.
164    * 
165    * @param queryConfig the query config handler
166    */
167   public void setQueryConfig(StandardQueryConfigHandler queryConfig) {
168     this.config = queryConfig;
169
170     if (this.processorPipeline != null) {
171       this.processorPipeline.setQueryConfigHandler(this.config);
172     }
173
174   }
175
176   /**
177    * Returns the query config handler used by this query parser
178    * 
179    * @return the query config handler
180    */
181   public QueryConfigHandler getQueryConfigHandler() {
182     return this.config;
183   }
184
185   /**
186    * Returns {@link QueryNodeProcessor} used to process the query node tree
187    * generated by the
188    * {@link org.apache.lucene.queryParser.standard.parser.StandardSyntaxParser}.
189    * 
190    * @return the query processor
191    */
192   public QueryNodeProcessor getQueryProcessor() {
193     return this.processorPipeline;
194   }
195
196   public ParseException generateParseException() {
197     return null;
198   }
199
200   public boolean getAllowLeadingWildcard() {
201
202     if (this.config != null) {
203       return this.config.get(ConfigurationKeys.ALLOW_LEADING_WILDCARD, false);
204     }
205
206     return false;
207
208   }
209
210   public MultiTermQuery.RewriteMethod getMultiTermRewriteMethod() {
211
212     if (this.config != null) {
213       return this.config.get(ConfigurationKeys.MULTI_TERM_REWRITE_METHOD,
214           MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT);
215     }
216
217     return MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;
218
219   }
220
221   public Resolution getDateResolution(String fieldName) {
222
223     if (this.config != null) {
224       FieldConfig fieldConfig = this.config.getFieldConfig(fieldName);
225
226       if (fieldConfig != null) {
227         return fieldConfig.get(ConfigurationKeys.DATE_RESOLUTION);
228       }
229
230     }
231
232     return null;
233
234   }
235
236   public boolean getEnablePositionIncrements() {
237
238     if (this.config != null) {
239       return this.config.get(ConfigurationKeys.ENABLE_POSITION_INCREMENTS,
240           false);
241     }
242
243     return false;
244
245   }
246
247   public float getFuzzyMinSim() {
248     return FuzzyQuery.defaultMinSimilarity;
249   }
250
251   public int getFuzzyPrefixLength() {
252     return FuzzyQuery.defaultPrefixLength;
253   }
254
255   public Locale getLocale() {
256
257     if (this.config != null) {
258       return this.config.get(ConfigurationKeys.LOCALE, Locale.getDefault());
259     }
260
261     return Locale.getDefault();
262
263   }
264
265   public boolean getLowercaseExpandedTerms() {
266
267     if (this.config != null) {
268       return this.config.get(ConfigurationKeys.LOWERCASE_EXPANDED_TERMS, true);
269     }
270
271     return true;
272
273   }
274
275   public int getPhraseSlop() {
276
277     if (this.config != null) {
278       return this.config.get(ConfigurationKeys.PHRASE_SLOP, 0);
279     }
280
281     return 0;
282
283   }
284
285   public Collator getRangeCollator() {
286
287     if (this.config != null) {
288       return this.config.get(ConfigurationKeys.RANGE_COLLATOR);
289     }
290
291     return null;
292
293   }
294
295   public boolean getUseOldRangeQuery() {
296     if (getMultiTermRewriteMethod() == MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE) {
297       return true;
298     } else {
299       return false;
300     }
301   }
302
303   public Query parse(String query) throws ParseException {
304
305     try {
306       QueryNode queryTree = this.syntaxParser.parse(query, getField());
307       queryTree = this.processorPipeline.process(queryTree);
308       return this.builder.build(queryTree);
309
310     } catch (QueryNodeException e) {
311       throw new ParseException("parse exception");
312     }
313
314   }
315
316   public void setAllowLeadingWildcard(boolean allowLeadingWildcard) {
317     this.qpHelper.setAllowLeadingWildcard(allowLeadingWildcard);
318   }
319
320   public void setMultiTermRewriteMethod(MultiTermQuery.RewriteMethod method) {
321     this.qpHelper.setMultiTermRewriteMethod(method);
322   }
323
324   public void setDateResolution(Resolution dateResolution) {
325     this.qpHelper.setDateResolution(dateResolution);
326   }
327
328   private Map<CharSequence, DateTools.Resolution> dateRes = new HashMap<CharSequence, DateTools.Resolution>();
329
330   public void setDateResolution(String fieldName, Resolution dateResolution) {
331     dateRes.put(fieldName, dateResolution);
332     this.qpHelper.setDateResolution(dateRes);
333   }
334
335   public void setDefaultOperator(Operator op) {
336
337     this.qpHelper
338         .setDefaultOperator(OR_OPERATOR.equals(op) ? org.apache.lucene.queryParser.standard.config.DefaultOperatorAttribute.Operator.OR
339             : org.apache.lucene.queryParser.standard.config.DefaultOperatorAttribute.Operator.AND);
340
341   }
342
343   public Operator getDefaultOperator() {
344
345     if (this.config != null) {
346
347       return (this.config.get(ConfigurationKeys.DEFAULT_OPERATOR, org.apache.lucene.queryParser.standard.config.StandardQueryConfigHandler.Operator.OR)
348            == org.apache.lucene.queryParser.standard.config.StandardQueryConfigHandler.Operator.AND) ? AND_OPERATOR
349           : OR_OPERATOR;
350
351     }
352
353     return OR_OPERATOR;
354
355   }
356
357   public void setEnablePositionIncrements(boolean enable) {
358     this.qpHelper.setEnablePositionIncrements(enable);
359   }
360
361   public void setFuzzyMinSim(float fuzzyMinSim) {
362     // TODO Auto-generated method stub
363
364   }
365
366   public void setFuzzyPrefixLength(int fuzzyPrefixLength) {
367     // TODO Auto-generated method stub
368
369   }
370
371   public void setLocale(Locale locale) {
372     this.qpHelper.setLocale(locale);
373   }
374
375   public void setLowercaseExpandedTerms(boolean lowercaseExpandedTerms) {
376     this.qpHelper.setLowercaseExpandedTerms(lowercaseExpandedTerms);
377   }
378
379   public void setPhraseSlop(int phraseSlop) {
380     this.qpHelper.setDefaultPhraseSlop(phraseSlop);
381   }
382
383   public void setRangeCollator(Collator rc) {
384     this.qpHelper.setRangeCollator(rc);
385   }
386
387   public void setUseOldRangeQuery(boolean useOldRangeQuery) {
388     if (useOldRangeQuery) {
389       setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
390     } else {
391       setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT);
392     }
393   }
394
395   protected Query getPrefixQuery(String field, String termStr)
396       throws ParseException {
397     throw new UnsupportedOperationException();
398   }
399
400   protected Query getWildcardQuery(String field, String termStr)
401       throws ParseException {
402     throw new UnsupportedOperationException();
403   }
404
405   protected Query getFuzzyQuery(String field, String termStr,
406       float minSimilarity) throws ParseException {
407     throw new UnsupportedOperationException();
408   }
409
410   /** @deprecated Use {@link #getFieldQuery(String, String, boolean)} instead */
411   @Deprecated
412   protected Query getFieldQuery(String field, String queryText) throws ParseException {
413     return getFieldQuery(field, queryText, true);
414   }
415
416   /**
417    * @exception ParseException throw in overridden method to disallow
418    */
419   protected Query getFieldQuery(String field, String queryText, boolean quoted)
420       throws ParseException {
421     throw new UnsupportedOperationException();
422   }
423
424   protected Query getBooleanQuery(List<BooleanClause> clauses, boolean disableCoord)
425       throws ParseException {
426     throw new UnsupportedOperationException();
427   }
428
429   /**
430    * Base implementation delegates to {@link #getFieldQuery(String,String)}.
431    * This method may be overridden, for example, to return a SpanNearQuery
432    * instead of a PhraseQuery.
433    * 
434    * @exception ParseException throw in overridden method to disallow
435    */
436   protected Query getFieldQuery(String field, String queryText, int slop)
437       throws ParseException {
438     throw new UnsupportedOperationException();
439   }
440
441   /**
442    * @exception ParseException throw in overridden method to disallow
443    */
444   protected Query getRangeQuery(String field, String part1, String part2,
445       boolean inclusive) throws ParseException {
446     throw new UnsupportedOperationException();
447   }
448
449 }