📄 queryparser.jjt
字号:
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */options { STATIC=false; JAVA_UNICODE_ESCAPE=true; USER_CHAR_STREAM=true;}PARSER_BEGIN(QueryParser)package org.apache.jackrabbit.core.query.lucene.fulltext;import java.util.Vector;import java.io.*;import java.text.*;import java.util.*;import org.apache.lucene.index.Term;import org.apache.lucene.analysis.*;import org.apache.lucene.document.*;import org.apache.lucene.search.*;import org.apache.jackrabbit.core.query.lucene.WildcardQuery;/** * This class is generated by JavaCC. The only method that clients should need * to call is <a href="#parse">parse()</a>. * * The syntax for query strings is as follows: * A Query is a series of clauses. * A clause may be prefixed by: * <ul> * <li> a plus (<code>+</code>) or a minus (<code>-</code>) sign, indicating * that the clause is required or prohibited respectively; or * <li> a term followed by a colon, indicating the field to be searched. * This enables one to construct queries which search multiple fields. * </ul> * * A clause may be either: * <ul> * <li> a term, indicating all the documents that contain this term; or * <li> a nested query, enclosed in parentheses. Note that this may be used * with a <code>+</code>/<code>-</code> prefix to require any of a set of * terms. * </ul> * * Thus, in BNF, the query grammar is: * <pre> * Query ::= ( Clause )* * Clause ::= ["+", "-"] [<TERM> ":"] ( <TERM> | "(" Query ")" ) * </pre> * * <p> * Examples of appropriately formatted queries can be found in the <a * href="http://jakarta.apache.org/lucene/src/test/org/apache/lucene/queryParser/TestQueryParser.java">test cases</a>. * </p> * * @author Brian Goetz * @author Peter Halacsy * @author Tatu Saloranta */public class QueryParser { private static final int CONJ_NONE = 0; private static final int CONJ_AND = 1; private static final int CONJ_OR = 2; private static final int MOD_NONE = 0; private static final int MOD_NOT = 10; private static final int MOD_REQ = 11; public static final int DEFAULT_OPERATOR_OR = 0; public static final int DEFAULT_OPERATOR_AND = 1; /** The actual operator that parser uses to combine query terms */ private int operator = DEFAULT_OPERATOR_OR; /** * Whether terms of wildcard and prefix queries are to be automatically * lower-cased or not. Default is <code>true</code>. */ boolean lowercaseWildcardTerms = true; Analyzer analyzer; String field; int phraseSlop = 0; float fuzzyMinSim = FuzzyQuery.defaultMinSimilarity; Locale locale = Locale.getDefault(); /** Parses a query string, returning a {@link org.apache.lucene.search.Query}. * @param query the query string to be parsed. * @param field the default field for query terms. * @param analyzer used to find terms in the query text. * @throws ParseException if the parsing fails */ static public Query parse(String query, String field, Analyzer analyzer) throws ParseException { QueryParser parser = new QueryParser(field, analyzer); return parser.parse(query); } /** Constructs a query parser. * @param f the default field for query terms. * @param a used to find terms in the query text. */ public QueryParser(String f, Analyzer a) { this(new FastCharStream("")); analyzer = a; field = f; } /** Parses a query string, returning a * <a href="lucene.search.Query.html">Query</a>. * @param query the query string to be parsed. * @throws ParseException if the parsing fails */ public Query parse(String query) throws ParseException { ReInit(new FastCharStream(query)); try { return Query(field); } catch (TokenMgrError tme) { throw new ParseException(tme.getMessage()); } catch (BooleanQuery.TooManyClauses tmc) { throw new ParseException("Too many boolean clauses"); } } /** * @return Returns the analyzer. */ public Analyzer getAnalyzer() { return analyzer; } /** * @return Returns the field. */ public String getField() { return field; } /** * Get the default minimal similarity for fuzzy queries. */ public float getFuzzyMinSim() { return fuzzyMinSim; } /** *Set the default minimum similarity for fuzzy queries. */ public void setFuzzyMinSim(float fuzzyMinSim) { this.fuzzyMinSim = fuzzyMinSim; } /** * Sets the default slop for phrases. If zero, then exact phrase matches * are required. Default value is zero. */ public void setPhraseSlop(int phraseSlop) { this.phraseSlop = phraseSlop; } /** * Gets the default slop for phrases. */ public int getPhraseSlop() { return phraseSlop; } /** * Sets the boolean operator of the QueryParser. * In classic mode (<code>DEFAULT_OPERATOR_OR</code>) terms without any modifiers * are considered optional: for example <code>capital of Hungary</code> is equal to * <code>capital OR of OR Hungary</code>.<br/> * In <code>DEFAULT_OPERATOR_AND</code> terms are considered to be in conjuction: the * above mentioned query is parsed as <code>capital AND of AND Hungary</code> */ public void setOperator(int operator) { this.operator = operator; } /** * Gets implicit operator setting, which will be either DEFAULT_OPERATOR_AND * or DEFAULT_OPERATOR_OR. */ public int getOperator() { return operator; } public void setLowercaseWildcardTerms(boolean lowercaseWildcardTerms) { this.lowercaseWildcardTerms = lowercaseWildcardTerms; } public boolean getLowercaseWildcardTerms() { return lowercaseWildcardTerms; } /** * Set locale used by date range parsing. */ public void setLocale(Locale locale) { this.locale = locale; } /** * Returns current locale, allowing access by subclasses. */ public Locale getLocale() { return locale; } protected void addClause(Vector clauses, int conj, int mods, Query q) { boolean required, prohibited; // If this term is introduced by AND, make the preceding term required, // unless it's already prohibited if (clauses.size() > 0 && conj == CONJ_AND) { BooleanClause c = (BooleanClause) clauses.elementAt(clauses.size()-1); if (!c.isProhibited()) c.setOccur(BooleanClause.Occur.MUST); } if (clauses.size() > 0 && operator == DEFAULT_OPERATOR_AND && conj == CONJ_OR) { // If this term is introduced by OR, make the preceding term optional, // unless it's prohibited (that means we leave -a OR b but +a OR b-->a OR b) // notice if the input is a OR b, first term is parsed as required; without // this modification a OR b would parsed as +a OR b BooleanClause c = (BooleanClause) clauses.elementAt(clauses.size()-1); if (!c.isProhibited()) c.setOccur(BooleanClause.Occur.SHOULD); } // We might have been passed a null query; the term might have been // filtered away by the analyzer. if (q == null) return; if (operator == DEFAULT_OPERATOR_OR) { // We set REQUIRED if we're introduced by AND or +; PROHIBITED if // introduced by NOT or -; make sure not to set both. prohibited = (mods == MOD_NOT); required = (mods == MOD_REQ); if (conj == CONJ_AND && !prohibited) { required = true; } } else { // We set PROHIBITED if we're introduced by NOT or -; We set REQUIRED // if not PROHIBITED and not introduced by OR prohibited = (mods == MOD_NOT); required = (!prohibited && conj != CONJ_OR); } BooleanClause.Occur occur = null; if (required) { occur = BooleanClause.Occur.MUST; } else if (prohibited) { occur = BooleanClause.Occur.MUST_NOT; } else { occur = BooleanClause.Occur.SHOULD; } clauses.addElement(new BooleanClause(q, occur)); } /** * Note that parameter analyzer is ignored. Calls inside the parser always * use class member analyser. This method will be deprecated and substituted * by {@link #getFieldQuery(String, String)} in future versions of Lucene. * Currently overwriting either of these methods works. * * @exception ParseException throw in overridden method to disallow */ protected Query getFieldQuery(String field, Analyzer analyzer, String queryText) throws ParseException { return getFieldQuery(field, queryText); } /** * @exception ParseException throw in overridden method to disallow */ protected Query getFieldQuery(String field, String queryText) throws ParseException { // Use the analyzer to get all the tokens, and then build a TermQuery, // PhraseQuery, or nothing based on the term count TokenStream source = analyzer.tokenStream(field, new StringReader(queryText)); Vector v = new Vector(); org.apache.lucene.analysis.Token t; while (true) { try { t = source.next(); } catch (IOException e) { t = null; } if (t == null) break; v.addElement(t.termText()); } try { source.close(); } catch (IOException e) { // ignore } if (v.size() == 0) return null; else if (v.size() == 1) return new TermQuery(new Term(field, (String) v.elementAt(0))); else { PhraseQuery q = new PhraseQuery(); q.setSlop(phraseSlop); for (int i=0; i<v.size(); i++) { q.add(new Term(field, (String) v.elementAt(i))); } return q; } } /** * Base implementation delegates to {@link #getFieldQuery(String, Analyzer, String)}. * This method may be overwritten, for example, to return * a SpanNearQuery instead of a PhraseQuery. * * Note that parameter analyzer is ignored. Calls inside the parser always * use class member analyser. This method will be deprecated and substituted * by {@link #getFieldQuery(String, String, int)} in future versions of Lucene. * Currently overwriting either of these methods works. * * @exception ParseException throw in overridden method to disallow */ protected Query getFieldQuery(String field, Analyzer analyzer, String queryText, int slop) throws ParseException { return getFieldQuery(field, queryText, slop); } /** * Base implementation delegates to {@link #getFieldQuery(String,String)}. * This method may be overridden, for example, to return * a SpanNearQuery instead of a PhraseQuery. * * @exception ParseException throw in overridden method to disallow */ protected Query getFieldQuery(String field, String queryText, int slop) throws ParseException { Query query = getFieldQuery(field, queryText); if (query instanceof PhraseQuery) { ((PhraseQuery) query).setSlop(slop); } return query; } /** * Note that parameter analyzer is ignored. Calls inside the parser always * use class member analyser. This method will be deprecated and substituted * by {@link #getRangeQuery(String, String, String, boolean)} in future versions of Lucene. * Currently overwriting either of these methods works. * * @exception ParseException throw in overridden method to disallow */ protected Query getRangeQuery(String field, Analyzer analyzer, String part1, String part2, boolean inclusive) throws ParseException { return getRangeQuery(field, part1, part2, inclusive); } /** * @exception ParseException throw in overridden method to disallow */ protected Query getRangeQuery(String field, String part1, String part2, boolean inclusive) throws ParseException { try { DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale); df.setLenient(true); Date d1 = df.parse(part1); Date d2 = df.parse(part2); part1 = DateField.dateToString(d1); part2 = DateField.dateToString(d2); } catch (Exception e) { } return new RangeQuery(new Term(field, part1), new Term(field, part2), inclusive); } /** * Factory method for generating query, given a set of clauses. * By default creates a boolean query composed of clauses passed in. * * Can be overridden by extending classes, to modify query being * returned. * * @param clauses Vector that contains {@link BooleanClause} instances * to join. * * @return Resulting {@link Query} object. * @exception ParseException throw in overridden method to disallow */ protected Query getBooleanQuery(Vector clauses) throws ParseException { BooleanQuery query = new BooleanQuery(); for (int i = 0; i < clauses.size(); i++) { query.add((BooleanClause)clauses.elementAt(i)); } return query; } /** * Factory method for generating a query. Called when parser * parses an input term token that contains one or more wildcard * characters (? and *), but is not a prefix term token (one
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -