`
wjboy49
  • 浏览: 274552 次
  • 性别: Icon_minigender_1
  • 来自: 湖南岳阳
社区版块
存档分类
最新评论

Lucene-2.3.1 源代码阅读学习(30)

阅读更多

关于Query的学习。

主要使用TermQuery和BooleanQuery,它们是最最基础的Query。

我感觉Query的灵活性太大了,这就使得它那么地具有魅力。

当用户提交了检索关键字以后,首先就是要根据这个关键字进行分析,因为不同的用户提交的关键词具有不同的特点,所以使用不同方式来构造Query是极其关键的,从而使提供的检索服务最大程度地满足用户的意愿。

先看看Query抽象类的继承关系,如图所示:

最简单最基础的就是构造一个TermQuery,根据词条本身直接来构造一个Query,从而进行检索。

Query类抽象类了进行检索所具有的共同特征,源代码实现如下所示:

package org.apache.lucene.search;

import java.io.IOException;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.lucene.index.IndexReader;

public abstract class Query implements java.io.Serializable, Cloneable {

// boost是一个非常重要的属性,它体现了检索到的Document的重要程度,Lucene默认值为1.0,当然可以自行设置
private float boost = 1.0f;                    

public void setBoost(float b) { boost = b; }

public float getBoost() { return boost; }

public abstract String toString(String field);

public String toString() {
    return toString("");
}

//    一个Query与一个Weight相关
protected Weight createWeight(Searcher searcher) throws IOException {
    throw new UnsupportedOperationException();
}

public Weight weight(Searcher searcher)
    throws IOException {
    Query query = searcher.rewrite(this);
    Weight weight = query.createWeight(searcher);
    float sum = weight.sumOfSquaredWeights();
    float norm = getSimilarity(searcher).queryNorm(sum);
    weight.normalize(norm);
    return weight;
}

//    重写一个Query
public Query rewrite(IndexReader reader) throws IOException {
    return this;
}

//    该方法主要是为复杂查询建立的,通过多个Query的合并来实现,比如,一个BooleanQuery可以是几个TermQuery的合并
public Query combine(Query[] queries) {
    HashSet uniques = new HashSet();
    for (int i = 0; i < queries.length; i++) {
      Query query = queries[i];
      BooleanClause[] clauses = null;
      //   是否需要将一个Query分割成多个查询子句的标志
      boolean splittable = (query instanceof BooleanQuery);    // 可见,这里是对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);
      }
    }
    // 如果只有一个查询子句,直接返回
    if(uniques.size() == 1){
        return (Query)uniques.iterator().next();
    }
    Iterator it = uniques.iterator();
    BooleanQuery result = new BooleanQuery(true);
    while (it.hasNext())
      result.add((Query) it.next(), BooleanClause.Occur.SHOULD);
    return result;
}

//    从构造的Query中提取出与该查询关联的词条,即用户键入的检索关键字构造的词条
public void extractTerms(Set terms) {
    // needs to be implemented by query subclasses
    throw new UnsupportedOperationException();
}


//    合并多个BooleanQuery,构造复杂查询
public static Query mergeBooleanQueries(Query[] queries) {
    HashSet allClauses = new HashSet();
    for (int i = 0; i < queries.length; i++) {
      BooleanClause[] clauses = ((BooleanQuery)queries[i]).getClauses();
      for (int j = 0; j < clauses.length; j++) {
        allClauses.add(clauses[j]);
      }
    }

    boolean coordDisabled =
      queries.length==0? false : ((BooleanQuery)queries[0]).isCoordDisabled();
    BooleanQuery result = new BooleanQuery(coordDisabled);
    Iterator i = allClauses.iterator();
    while (i.hasNext()) {
      result.add((BooleanClause)i.next());
    }
    return result;
}

//    获取与查询相关的Similarity(相似度)实例
public Similarity getSimilarity(Searcher searcher) {
    return searcher.getSimilarity();
}

//    Query是支持克隆的
public Object clone() {
    try {
      return (Query)super.clone();
    } catch (CloneNotSupportedException e) {
      throw new RuntimeException("Clone not supported: " + e.getMessage());
    }
}
}

上面出现了BooleanQuery,从字面可以了解到这种Query是基于逻辑运算的。BooleanQuery可以是多个子句的逻辑运算。从BooleanQuery的代码中可以看到,它支持子句的最大数量为1024:

private static int maxClauseCount = 1024;

但是,并非越多子句参与逻辑运算就越好,这里有个效率问题,因为多个子句的合并,要通过各自的Query之后,然后再进行这种逻辑运算,有时时间开销是不可取的。

BooleanClause是在一个BooleanQuery中子句。该类中定义了一个静态最终内部类Occur定义了BooleanQuery的运算符:

    public static final Occur MUST = new Occur("MUST");    // 与运算
    public static final Occur SHOULD = new Occur("SHOULD");    // 或运算
    public static final Occur MUST_NOT = new Occur("MUST_NOT");    // 非运算

可以通过上面三个算子对Query进行合并,实现复杂的查询操作。

编写一个例子,通过构造三个TermQuery,将他们添加(add)到一个BooleanQuery查询中,使用MUST与运算,如下所示:

package org.apache.lucene.shirdrn.main;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hit;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

public class BloeanQuerySearcher {

   public static void main(String[] args) {
   
    String indexPath = "E:\\Lucene\\myindex";
    try {
     IndexSearcher searcher = new IndexSearcher(indexPath);
    
     String keywordA = "的";
     Term termA = new Term("contents",keywordA);
     Query tQueryA = new TermQuery(termA);
    
     String keywordB = "是";
     Term termB = new Term("contents",keywordB);
     Query tQueryB = new TermQuery(termB);
    
     String keywordC = "在";
     Term termC = new Term("contents",keywordC);
     Query tQueryC = new TermQuery(termC);
    
     Term[] arrayTerm = new Term[]{null,null,null};
     arrayTerm[0] = termA;
     arrayTerm[1] = termB;
     arrayTerm[2] = termC;
    
     BooleanQuery bQuery = new BooleanQuery();
     bQuery.add(tQueryA,BooleanClause.Occur.MUST);
     bQuery.add(tQueryB,BooleanClause.Occur.MUST);
     bQuery.add(tQueryC,BooleanClause.Occur.MUST);

    
     Date startTime = new Date();
     Hits hits = searcher.search(bQuery);
     Iterator it = hits.iterator();
     System.out.println("********************************************************************");
     while(it.hasNext()){
      Hit hit = (Hit)it.next();
      System.out.println("Hit的ID 为 : "+hit.getId());
      System.out.println("Hit的score 为 : "+hit.getScore());
      System.out.println("Hit的boost 为 : "+hit.getBoost());
      System.out.println("Hit的toString 为 : "+hit.toString());
      System.out.println("Hit的Dcoment 为 : "+hit.getDocument());
      System.out.println("Hit的Dcoment 的 Fields 为 : "+hit.getDocument().getFields());
      for(int i=0;i<hit.getDocument().getFields().size();i++){
       Field field = (Field)hit.getDocument().getFields().get(i);
       System.out.println("      -------------------------------------------------------------");
       System.out.println("      Field的Name为 : "+field.name());
       System.out.println("      Field的stringValue为 : "+field.stringValue());
      }
      System.out.println("********************************************************************");
     }
     System.out.println("包含3个词条的Hits长度为 : "+hits.length());
     for(int i=0;i<searcher.docFreqs(arrayTerm).length;i++){
      System.out.println("包含3个词条的Document的数量为 : "+searcher.docFreqs(arrayTerm)[i]);
     }
     Date finishTime = new Date();
     long timeOfSearch = finishTime.getTime() - startTime.getTime();
     System.out.println("本次搜索所用的时间为 "+timeOfSearch+" ms");
    } catch (CorruptIndexException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
}

 

下面对各种逻辑运算的组合看一下效果:

1、第一种组合:

     bQuery.add(tQueryA,BooleanClause.Occur.MUST );
     bQuery.add(tQueryB,BooleanClause.Occur.MUST );
     bQuery.add(tQueryC,BooleanClause.Occur.MUST );

查询结果即是,同时包含三个词条(词条的文本内容为:的、在、是)的所有文档被检索出来。可以猜想一下,上面撒个词条:“的”、“是”、“在”在汉语中应该是出现频率非常高的,预期结果应该会查询出来较多的符合下面与运算条件的结果:

     bQuery.add(tQueryA,BooleanClause.Occur.MUST);
     bQuery.add(tQueryB,BooleanClause.Occur.MUST);
     bQuery.add(tQueryC,BooleanClause.Occur.MUST);

实际运行结果如下所示:

********************************************************************
Hit的ID 为 : 12
Hit的score 为 : 0.63582987
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [0] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\CustomKeyInfo.txt> stored/uncompressed,indexed<modified:200406041814>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\CustomKeyInfo.txt>, stored/uncompressed,indexed<modified:200406041814>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\CustomKeyInfo.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200406041814
********************************************************************
Hit的ID 为 : 24
Hit的score 为 : 0.6183762
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [1] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\FAQ.txt> stored/uncompressed,indexed<modified:200604130754>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\FAQ.txt>, stored/uncompressed,indexed<modified:200604130754>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\FAQ.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200604130754
********************************************************************
Hit的ID 为 : 63
Hit的score 为 : 0.53687334
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [2] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\疑问即时记录.txt> stored/uncompressed,indexed<modified:200711141408>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\疑问即时记录.txt>, stored/uncompressed,indexed<modified:200711141408>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\疑问即时记录.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200711141408
********************************************************************
Hit的ID 为 : 60
Hit的score 为 : 0.50429535
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [3] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\猫吉又有个忙,需要大家帮忙一下.txt> stored/uncompressed,indexed<modified:200706161112>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\猫吉又有个忙,需要大家帮忙一下.txt>, stored/uncompressed,indexed<modified:200706161112>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\猫吉又有个忙,需要大家帮忙一下.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200706161112
********************************************************************
Hit的ID 为 : 46
Hit的score 为 : 0.4266696
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [4] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\使用技巧集萃.txt> stored/uncompressed,indexed<modified:200511210413>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\使用技巧集萃.txt>, stored/uncompressed,indexed<modified:200511210413>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\使用技巧集萃.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200511210413
********************************************************************
Hit的ID 为 : 56
Hit的score 为 : 0.4056765
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [5] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\新1建 文本文档.txt> stored/uncompressed,indexed<modified:200710311142>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\新1建 文本文档.txt>, stored/uncompressed,indexed<modified:200710311142>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\新1建 文本文档.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200710311142
********************************************************************
Hit的ID 为 : 41
Hit的score 为 : 0.3852732
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [6] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\Update.txt> stored/uncompressed,indexed<modified:200707050028>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\Update.txt>, stored/uncompressed,indexed<modified:200707050028>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\Update.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200707050028
********************************************************************
Hit的ID 为 : 37
Hit的score 为 : 0.35885736
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [7] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\readme.txt> stored/uncompressed,indexed<modified:200803101314>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\readme.txt>, stored/uncompressed,indexed<modified:200803101314>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\readme.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200803101314
********************************************************************
Hit的ID 为 : 48
Hit的score 为 : 0.35885736
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [8] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\剑心补丁使用说明(readme).txt> stored/uncompressed,indexed<modified:200803101357>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\剑心补丁使用说明(readme).txt>, stored/uncompressed,indexed<modified:200803101357>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\剑心补丁使用说明(readme).txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200803101357
********************************************************************
Hit的ID 为 : 47
Hit的score 为 : 0.32808846
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [9] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\关系记录.txt> stored/uncompressed,indexed<modified:200802201145>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\关系记录.txt>, stored/uncompressed,indexed<modified:200802201145>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\关系记录.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200802201145
********************************************************************
包含3个词条的Hits长度为 : 10
包含3个词条的Document的数量为 : 23
包含3个词条的Document的数量为 : 12
包含3个词条的Document的数量为 : 14
本次搜索所用的时间为 203 ms

从上面测试可见,查询的记过具有10项,应该符合我们预期的假设的。

2、第二种组合:

     bQuery.add(tQueryA,BooleanClause.Occur.MUST_NOT );
     bQuery.add(tQueryB,BooleanClause.Occur.MUST );
     bQuery.add(tQueryC,BooleanClause.Occur.MUST );

 

即,把不包含词条“的”,但是同时包含词条“是”和“在”,查询出来的结果应该不会太多,中文的文章中“的”出现的频率很高很高,上面指定了MUST_NOT,非逻辑运算符,结果如下所示:

********************************************************************
Hit的ID 为 : 54
Hit的score 为 : 0.22303896
Hit的boost 为 : 1.0
Hit的toString 为 : Hit<org.apache.lucene.search.Hits@ab50cd [0] resolved>
Hit的Dcoment 为 : Document<stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\指定时间内关闭网页.txt> stored/uncompressed,indexed<modified:200111200742>>
Hit的Dcoment 的 Fields 为 : [stored/uncompressed,indexed<path:E:\Lucene\txt1\mytxt\指定时间内关闭网页.txt>, stored/uncompressed,indexed<modified:200111200742>]
      -------------------------------------------------------------
      Field的Name为 : path
      Field的stringValue为 : E:\Lucene\txt1\mytxt\指定时间内关闭网页.txt
      -------------------------------------------------------------
      Field的Name为 : modified
      Field的stringValue为 : 200111200742
********************************************************************
3个词条的Hits长度为 : 1
包含3个词条的Document的数量为 : 23
包含3个词条的Document的数量为 : 12
包含3个词条的Document的数量为 : 14
本次搜索所用的时间为 140 ms

符合查询条件的只有一项,只有记事本文件E:\Lucene\txt1\mytxt\指定时间内关闭网页.txt中满足查询条件,即该文件中一定没有词条“的”出现,但是同时包含词条“是”和“在”。

3、第三种组合:

     bQuery.add(tQueryA,BooleanClause.Occur.SHOULD );
     bQuery.add(tQueryB,BooleanClause.Occur.SHOULD );
     bQuery.add(tQueryC,BooleanClause.Occur.SHOULD );

即或操作,可想而知,满足条件的结果项应该是最多的(我的测试是24项)。

4、第四种组合:

     bQuery.add(tQueryA,BooleanClause.Occur.MUST_NOT );
     bQuery.add(tQueryB,BooleanClause.Occur.MUST_NOT );
     bQuery.add(tQueryC,BooleanClause.Occur.MUST_NOT );

不包含三个词条的查询部结果。如果是通常的文本,文本信息量较大,如果同时不包含“的”、“是”、“在”三个词条,结果是可想而知的,几乎检索不出来任何符合这一条件的结果集。

还有一点,用户通过键入关键字进行检索,不会有这样的用户:不想获取与自己键入关键字匹配的结果呢,其实这种组合没有意义的。

我的测试为:

********************************************************************
3个词条的Hits长度为 : 0
包含3个词条的Document的数量为 : 23
包含3个词条的Document的数量为 : 12
包含3个词条的Document的数量为 : 14
本次搜索所用的时间为 94 ms

如果你建立索引的数据源文件类似古代诗词曲那样的文本,可能检索出来的结果会很可观的。

5、第五种组合:

     bQuery.add(tQueryA,BooleanClause.Occur.SHOULD );
     bQuery.add(tQueryB,BooleanClause.Occur.MUST_NOT );
     bQuery.add(tQueryC,BooleanClause.Occur.MUST_NOT );

     bQuery.add(tQueryA,BooleanClause.Occur.MUST );
     bQuery.add(tQueryB,BooleanClause.Occur.MUST_NOT );
     bQuery.add(tQueryC,BooleanClause.Occur.MUST_NOT );

经过测试,可以得知,上面的这两种组合检索得到的结果集是一样的。也就是说,SHOULD在与MUST_NOT进行组合的时候,其实就是MUST在和MUST_NOT进行组合。

6、第六种组合:

     bQuery.add(tQueryA,BooleanClause.Occur.SHOULD );
     bQuery.add(tQueryB,BooleanClause.Occur.MUST );
     bQuery.add(tQueryC,BooleanClause.Occur.MUST );

其实这种组合与SHOULD没有任何关系了,相当于下面的2个MUST的组合:

     bQuery.add(tQueryB,BooleanClause.Occur.MUST );
     bQuery.add(tQueryC,BooleanClause.Occur.MUST );

这两种组合检索出来的结果集是一样的。

总结

使用BooleanQuery进行查询,它工作的机制是这样的:

1、先对BooleanQuery中的每个子句分别进行查询,得到多个结果集;

2、对BooleanQuery的各个子句得到的结果集,进行集合的运算(交、并、非)。

最终,集合运算的结果就是显示给用户的,与用户查询条件匹配的记录。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics