⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 queryparser.jj

📁 Lucene a java open-source SearchEngine Framework
💻 JJ
📖 第 1 页 / 共 3 页
字号:
    if (fieldToDateResolution == null) {      // lazily initialize HashMap      fieldToDateResolution = new HashMap();    }        fieldToDateResolution.put(fieldName, dateResolution);  }  /**   * Returns the date resolution that is used by RangeQueries for the given field.    * Returns null, if no default or field specific date resolution has been set   * for the given field.   *   */  public DateTools.Resolution getDateResolution(String fieldName) {    if (fieldName == null) {      throw new IllegalArgumentException("Field cannot be null.");    }        if (fieldToDateResolution == null) {      // no field specific date resolutions set; return default date resolution instead      return this.dateResolution;    }        DateTools.Resolution resolution = (DateTools.Resolution) fieldToDateResolution.get(fieldName);    if (resolution == null) {      // no date resolutions set for the given field; return default date resolution instead      resolution = this.dateResolution;    }        return resolution;  }  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 == AND_OPERATOR && 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 == OR_OPERATOR) {      // 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);    }    if (required && !prohibited)      clauses.addElement(new BooleanClause(q, BooleanClause.Occur.MUST));    else if (!required && !prohibited)      clauses.addElement(new BooleanClause(q, BooleanClause.Occur.SHOULD));    else if (!required && prohibited)      clauses.addElement(new BooleanClause(q, BooleanClause.Occur.MUST_NOT));    else      throw new RuntimeException("Clause cannot be both required and prohibited");  }  /**   * @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;    int positionCount = 0;    boolean severalTokensAtSamePosition = false;    while (true) {      try {        t = source.next();      }      catch (IOException e) {        t = null;      }      if (t == null)        break;      v.addElement(t);      if (t.getPositionIncrement() != 0)        positionCount += t.getPositionIncrement();      else        severalTokensAtSamePosition = true;    }    try {      source.close();    }    catch (IOException e) {      // ignore    }    if (v.size() == 0)      return null;    else if (v.size() == 1) {      t = (org.apache.lucene.analysis.Token) v.elementAt(0);      return new TermQuery(new Term(field, t.termText()));    } else {      if (severalTokensAtSamePosition) {        if (positionCount == 1) {          // no phrase query:          BooleanQuery q = new BooleanQuery(true);          for (int i = 0; i < v.size(); i++) {            t = (org.apache.lucene.analysis.Token) v.elementAt(i);            TermQuery currentQuery = new TermQuery(                new Term(field, t.termText()));            q.add(currentQuery, BooleanClause.Occur.SHOULD);          }          return q;        }        else {          // phrase query:          MultiPhraseQuery mpq = new MultiPhraseQuery();          mpq.setSlop(phraseSlop);                    List multiTerms = new ArrayList();          int position = -1;          for (int i = 0; i < v.size(); i++) {            t = (org.apache.lucene.analysis.Token) v.elementAt(i);            if (t.getPositionIncrement() > 0 && multiTerms.size() > 0) {              if (enablePositionIncrements) {                mpq.add((Term[])multiTerms.toArray(new Term[0]),position);              } else {                mpq.add((Term[])multiTerms.toArray(new Term[0]));              }              multiTerms.clear();            }            position += t.getPositionIncrement();            multiTerms.add(new Term(field, t.termText()));          }          if (enablePositionIncrements) {            mpq.add((Term[])multiTerms.toArray(new Term[0]),position);          } else {            mpq.add((Term[])multiTerms.toArray(new Term[0]));          }          return mpq;        }      }      else {        PhraseQuery pq = new PhraseQuery();        pq.setSlop(phraseSlop);        int position = -1;        for (int i = 0; i < v.size(); i++) {          t = (org.apache.lucene.analysis.Token) v.elementAt(i);          if (enablePositionIncrements) {            position += t.getPositionIncrement();            pq.add(new Term(field, t.termText()),position);          } else {            pq.add(new Term(field, t.termText()));          }        }        return pq;      }    }  }  /**   * 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);    }    if (query instanceof MultiPhraseQuery) {      ((MultiPhraseQuery) query).setSlop(slop);    }    return query;  }  /**   * @exception ParseException throw in overridden method to disallow   */  protected Query getRangeQuery(String field,                                String part1,                                String part2,                                boolean inclusive) throws ParseException  {    if (lowercaseExpandedTerms) {      part1 = part1.toLowerCase();      part2 = part2.toLowerCase();    }    try {      DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);      df.setLenient(true);      Date d1 = df.parse(part1);      Date d2 = df.parse(part2);      if (inclusive) {        // The user can only specify the date, not the time, so make sure        // the time is set to the latest possible time of that date to really        // include all documents:        Calendar cal = Calendar.getInstance(locale);        cal.setTime(d2);        cal.set(Calendar.HOUR_OF_DAY, 23);        cal.set(Calendar.MINUTE, 59);        cal.set(Calendar.SECOND, 59);        cal.set(Calendar.MILLISECOND, 999);        d2 = cal.getTime();      }      DateTools.Resolution resolution = getDateResolution(field);      if (resolution == null) {        // no default or field specific date resolution has been set,        // use deprecated DateField to maintain compatibilty with        // pre-1.9 Lucene versions.        part1 = DateField.dateToString(d1);        part2 = DateField.dateToString(d2);      } else {        part1 = DateTools.dateToString(d1, resolution);        part2 = DateTools.dateToString(d2, resolution);      }    }    catch (Exception e) { }    if(useOldRangeQuery)    {	    return new RangeQuery(new Term(field, part1),                          new Term(field, part2),                          inclusive);    }    else    {      return new ConstantScoreRangeQuery(field,part1,part2,inclusive,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 {    return getBooleanQuery(clauses, false);  }  /**   * 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.   * @param disableCoord true if coord scoring should be disabled.   *   * @return Resulting {@link Query} object.   * @exception ParseException throw in overridden method to disallow   */  protected Query getBooleanQuery(Vector clauses, boolean disableCoord)    throws ParseException  {    if (clauses.size()==0) {      return null; // all clause words were filtered away by the analyzer.    }    BooleanQuery query = new BooleanQuery(disableCoord);    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   * that has just a single * character at the end)   *<p>   * Depending on settings, prefix term may be lower-cased   * automatically. It will not go through the default Analyzer,   * however, since normal Analyzers are unlikely to work properly   * with wildcard templates.   *<p>   * Can be overridden by extending classes, to provide custom handling for   * wildcard queries, which may be necessary due to missing analyzer calls.   *   * @param field Name of the field query will use.   * @param termStr Term token that contains one or more wild card   *   characters (? or *), but is not simple prefix term   *   * @return Resulting {@link Query} built for the term   * @exception ParseException throw in overridden method to disallow   */  protected Query getWildcardQuery(String field, String termStr) throws ParseException  {    if ("*".equals(field)) {      if ("*".equals(termStr)) return new MatchAllDocsQuery();    }    if (!allowLeadingWildcard && (termStr.startsWith("*") || termStr.startsWith("?")))      throw new ParseException("'*' or '?' not allowed as first character in WildcardQuery");    if (lowercaseExpandedTerms) {      termStr = termStr.toLowerCase();    }    Term t = new Term(field, termStr);    return new WildcardQuery(t);  }  /**   * Factory method for generating a query (similar to   * {@link #getWildcardQuery}). Called when parser parses an input term   * token that uses prefix notation; that is, contains a single '*' wildcard   * character as its last character. Since this is a special case   * of generic wildcard term, and such a query can be optimized easily,   * this usually results in a different query object.   *<p>   * Depending on settings, a prefix term may be lower-cased   * automatically. It will not go through the default Analyzer,   * however, since normal Analyzers are unlikely to work properly   * with wildcard templates.   *<p>   * Can be overridden by extending classes, to provide custom handling for   * wild card queries, which may be necessary due to missing analyzer calls.   *   * @param field Name of the field query will use.   * @param termStr Term token to use for building term for the query   *    (<b>without</b> trailing '*' character!)   *   * @return Resulting {@link Query} built for the term   * @exception ParseException throw in overridden method to disallow   */  protected Query getPrefixQuery(String field, String termStr) throws ParseException  {    if (!allowLeadingWildcard && termStr.startsWith("*"))      throw new ParseException("'*' not allowed as first character in PrefixQuery");    if (lowercaseExpandedTerms) {      termStr = termStr.toLowerCase();    }    Term t = new Term(field, termStr);    return new PrefixQuery(t);  }     /**   * Factory method for generating a query (similar to   * {@link #getWildcardQuery}). Called when parser parses   * an input term token that has the fuzzy suffix (~) appended.   *   * @param field Name of the field query will use.   * @param termStr Term token to use for building term for the query   *   * @return Resulting {@link Query} built for the term   * @exception ParseException throw in overridden method to disallow

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -