lucene query

在lucene的搜索中,最重要的无疑就是对query的理解和掌握了。这里扒拉一下源码(版本3.5.0)的query和query实现:

query是一个抽象类,实现类有以下几个:

termQuery

multiTermQuery

booleanQuery*

wildCardQuery

PhraseQuery

FuzzyQuery

TermRangeQuery

NumericRangeQuery

SpanQuery

/** The abstract base class for queries.
    <p>Instantiable subclasses are:
    <ul>
    <li> {@link TermQuery}
    <li> {@link MultiTermQuery}
    <li> {@link BooleanQuery}
    <li> {@link WildcardQuery}
    <li> {@link PhraseQuery}
    <li> {@link PrefixQuery}
    <li> {@link MultiPhraseQuery}
    <li> {@link FuzzyQuery}
    <li> {@link TermRangeQuery}
    <li> {@link NumericRangeQuery}
    <li> {@link org.apache.lucene.search.spans.SpanQuery}
    </ul>
    <p>A parser for queries is contained in:
    <ul>
    <li>{@link org.apache.lucene.queryParser.QueryParser QueryParser}
    </ul>
*/
public abstract class Query implements java.io.Serializable, Cloneable {
  private float boost = 1.0f;                     // query boost factor

  /** Sets the boost for this query clause to <code>b</code>.  Documents
   * matching this clause will (in addition to the normal weightings) have
   * their score multiplied by <code>b</code>.
   */
  public void setBoost(float b) { boost = b; }

  /** Gets the boost for this clause.  Documents matching
   * this clause will (in addition to the normal weightings) have their score
   * multiplied by <code>b</code>.   The boost is 1.0 by default.
   */
  public float getBoost() { return boost; }

  /** Prints a query to a string, with <code>field</code> assumed to be the
   * default field and omitted.
   * <p>The representation used is one that is supposed to be readable
   * by {@link org.apache.lucene.queryParser.QueryParser QueryParser}. However,
   * there are the following limitations:
   * <ul>
   *  <li>If the query was created by the parser, the printed
   *  representation may not be exactly what was parsed. For example,
   *  characters that need to be escaped will be represented without
   *  the required backslash.</li>
   * <li>Some of the more complicated queries (e.g. span queries)
   *  don‘t have a representation that can be parsed by QueryParser.</li>
   * </ul>
   */
  public abstract String toString(String field);

  /** Prints a query to a string. */
  @Override
  public String toString() {
    return toString("");
  }

  /**
   * Expert: Constructs an appropriate Weight implementation for this query.
   *
   * <p>
   * Only implemented by primitive queries, which re-write to themselves.
   */
  public Weight createWeight(Searcher searcher) throws IOException {
    throw new UnsupportedOperationException("Query " + this + " does not implement createWeight");
  }

  /**
   * Expert: Constructs and initializes a Weight for a <b>top-level</b> query.
   * @deprecated never ever use this method in {@link Weight} implementations.
   * Subclasses of {@code Query} should use {@link #createWeight}, instead.
   */
  @Deprecated
  public final Weight weight(Searcher searcher) throws IOException {
    return searcher.createNormalizedWeight(this);
  }

  /** Expert: called to re-write queries into primitive queries. For example,
   * a PrefixQuery will be rewritten into a BooleanQuery that consists
   * of TermQuerys.
   */
  public Query rewrite(IndexReader reader) throws IOException {
    return this;
  }

  /** Expert: called when re-writing queries under MultiSearcher.
   *
   * Create a single query suitable for use by all subsearchers (in 1-1
   * correspondence with queries). This is an optimization of the OR of
   * all queries. We handle the common optimization cases of equal
   * queries and overlapping clauses of boolean OR queries (as generated
   * by MultiTermQuery.rewrite()).
   * Be careful overriding this method as queries[0] determines which
   * method will be called and is not necessarily of the same type as
   * the other queries.
  */
  public Query combine(Query[] queries) {
    HashSet<Query> uniques = new HashSet<Query>();
    for (int i = 0; i < queries.length; i++) {
      Query query = queries[i];
      BooleanClause[] clauses = null;
      // check if we can split the query into clauses
      boolean splittable = (query instanceof BooleanQuery);
      if(splittable){
        BooleanQuery bq = (BooleanQuery) query;
        splittable = bq.isCoordDisabled();
        clauses = bq.getClauses();
        for (int j = 0; splittable && j < clauses.length; j++) {
          splittable = (clauses[j].getOccur() == BooleanClause.Occur.SHOULD);
        }
      }
      if(splittable){
        for (int j = 0; j < clauses.length; j++) {
          uniques.add(clauses[j].getQuery());
        }
      } else {
        uniques.add(query);
      }
    }
    // optimization: if we have just one query, just return it
    if(uniques.size() == 1){
        return uniques.iterator().next();
    }
    BooleanQuery result = new BooleanQuery(true);
    for (final Query query : uniques)
      result.add(query, BooleanClause.Occur.SHOULD);
    return result;
  }

  /**
   * Expert: adds all terms occurring in this query to the terms set. Only
   * works if this query is in its {@link #rewrite rewritten} form.
   *
   * @throws UnsupportedOperationException if this query is not yet rewritten
   */
  public void extractTerms(Set<Term> terms) {
    // needs to be implemented by query subclasses
    throw new UnsupportedOperationException();
  }

  /** Expert: merges the clauses of a set of BooleanQuery‘s into a single
   * BooleanQuery.
   *
   *<p>A utility for use by {@link #combine(Query[])} implementations.
   */
  public static Query mergeBooleanQueries(BooleanQuery... queries) {
    HashSet<BooleanClause> allClauses = new HashSet<BooleanClause>();
    for (BooleanQuery booleanQuery : queries) {
      for (BooleanClause clause : booleanQuery) {
        allClauses.add(clause);
      }
    }

    boolean coordDisabled =
      queries.length==0? false : queries[0].isCoordDisabled();
    BooleanQuery result = new BooleanQuery(coordDisabled);
    for(BooleanClause clause2 : allClauses) {
      result.add(clause2);
    }
    return result;
  }
时间: 2024-12-13 03:22:13

lucene query的相关文章

Lucene Query Term Weighting

方法 1 public static Query TermWeighting(Query tquery,Map<String,Float>term2weight){ 2 BooleanQuery nquery = new BooleanQuery(); 3 Set<Term> terms = new HashSet<Term>(); 4 tquery.extractTerms(terms); 5 for(Term itr : terms){ 6 float weight

Lucene Query种类

1.3. 按词条搜索-TermQuery Query query = null; query=new TermQuery(new Term("name","word1 a and")); hits=searcher.search(query);// 查找 name:word1 a and 共0个结果 System.out.println("查找 "+query.toString()+" 共" + hits.length() +

使用lucene query的CharFilter 去掉字符中的script脚本和html标签

1.准备数据,这里我从数据库读取一个带有html标签和script脚本的数据 代码: @Before public void init(){ SQLService sqlService = new SQLService(); sqlService.regist(null); BaseDao bd = new BaseDao(); String sql = "select * from t where title like '% 每天读一遍,舌头更无敌%'"; lists = bd.ge

lucene、lucene.NET详细使用与优化详解

lucene.lucene.NET详细使用与优化详解 2010-02-01 13:51:11 分类: Linux 1 lucene简介1.1 什么是luceneLucene是一个全文搜索框架,而不是应用产品.因此它并不像www.baidu.com 或者google Desktop那么拿来就能用,它只是提供了一种工具让你能实现这些产品. 1.2 lucene能做什么要 回答这个问题,先要了解lucene的本质.实际上lucene的功能很单一,说到底,就是你给它若干个字符串,然后它为你提供一个全文搜

Lucene - CustomScoreQuery 自定义排序

在某些场景需要做自定义排序(非单值字段排序.非文本相关度排序),除了自己重写collect.weight,可以借助CustomScoreQuery. 场景:根据tag字段中标签的数量进行排序(tag字段中,标签的数量越多得分越高) public class CustomScoreTest { public static void main(String[] args) throws IOException { Directory dir = new RAMDirectory(); Analyze

lucene使用与优化

lucene使用与优化 1 lucene简介 1.1 什么是lucene Lucene是一个全文搜索框架,而不是应用产品.因此它并不像www.baidu.com 或者google Desktop那么拿来就能用,它只是提供了一种工具让你能实现这些产品.1.2 lucene能做什么 要回答这个问题,先要了解lucene的本质.实际上lucene的功能很单一,说到底,就是你给它若干个字符串,然后它为你提供一个全文搜索服务,告诉你你要搜索的关键词出现在哪里.知道了这个本质,你就可以发挥想象做任何符合这个

来自官方的Range Query查询介绍【全英文】

Matches documents with fields that have terms within a certain range. The type of the Lucene query depends on the field type, for string fields, the TermRangeQuery, while for number/date fields, the query is a NumericRangeQuery. The following example

Solr 使用自定义 Query Parser(短语查询,精准查询)

原文出处:http://blog.chenlb.com/2010/08/solr-use-custom-query-parser.html 由于 Solr 默认的 Query Parser 生成的 Query 一般是 “短语查询”,导致只有很精确的结果才被搜索出来.大部分时候我们要分词后的 BooleanQuery.一年半前有篇关于 solr 使用自定义的 QueryParser 的文章.使用这个方法在 solr 中可以用自己的 Query Parser. 按照那篇文章,分别扩展:QParser

lucene 各种查询方式

各种查询方式一:使用QueryParser与查询语法.(会使用分词器) MultiFieldQueryParser查询字符串 ------------------------> Query对象 例如:上海 AND 天气上海 OR 天气上海新闻 AND site:news.163.com... 方式二:直接创建Query的实例(子类的),不会使用分词器new TermQuery(..);new BooleanQuery(..); package cn.itcast.i_query; import