`
caocao
  • 浏览: 270252 次
  • 来自: 上海
社区版块
存档分类
最新评论

Lucene Hack之通过缩小搜索结果集来提升性能 (2)

    博客分类:
  • Java
阅读更多
作者:caocao(网络隐士),http://www.caocao.namehttp://www.caocao.mobi
转载请注明来源:http://www.iteye.com/topic/80073

书接前文(http://www.iteye.com/topic/78884),上回说了个大致的原理,这回开始上代码。

五、原则
1、不改动lucene-core的代码
肆意改动lucene-core的代码实在是很不道德的事情,而且会导致后期维护升级的大量问题。如果真的有这等迫切需求,还不如加入lucene开发组,尽一份绵薄之力。看官说了,隐士你怎么不去啊,唉,代码比较丑陋,没脸去人家那里,后文详述。
2、不改动lucene索引文件格式
道理同上。
3、替换常规搜索的接口尽量少
这样可以方便来回切换标准搜索和这个搜索,减小代码修改、维护的成本。
4、命名规范
所有增加的类名均以Inaccurate开头,其余遵循lucene命名规范。

六、限制
1、隐士只做了BooleanWeight2的替代品,如果Weight不是BooleanWeight2,则等同于常规搜索。
2、如果搜索结果集小于等于最大允许的结果集,则等同于常规搜索。

七、文件
org.apache.lucene.search
    InaccurateBooleanScorer2.java // BooleanScorer2的替代品
    InaccurateBooleanWeight2.java // BooleanWeight2的替代品
    InaccurateHit.java // Hit的替代品
    InaccurateHitIterator.java // HitIterator的替代品
    InaccurateHits.java // Hits的替代品
    InaccurateIndexSearcher.java // IndexSearcher的替代品
org.apache.lucene.util
    InaccurateResultAggregation.java // 放搜索统计信息的value object


八、实战
1、InaccurateIndexSearcher
InaccurateIndexSearcher extends IndexSearcher,结构很简单,增加了两个成员变量:maxNumberOfDocs和inaccurateResultAggregation,以及几个methods。
丑陋的部分来了:
public void search(Weight weight, Filter filter, final HitCollector results, boolean ascending) throws IOException {
...
  if (weight.getClass().getSimpleName().equals("BooleanWeight2")) { // hook BooleanWeight2
   InaccurateBooleanWeight2 inaccurateBooleanWeight2 = new InaccurateBooleanWeight2(
     this, weight.getQuery());
   float sum = inaccurateBooleanWeight2.sumOfSquaredWeights();
   float norm = this.getSimilarity().queryNorm(sum);
   inaccurateBooleanWeight2.normalize(norm); // bad smell
   InaccurateBooleanScorer2 inaccurateBooleanScorer2 = inaccurateBooleanWeight2
     .getInaccurateBooleanScorer2(reader, maxNumberOfDocs);
   if (inaccurateBooleanScorer2 != null) {
    inaccurateResultAggregation = inaccurateBooleanScorer2
      .getInaccurateTopAggregation(collector, ascending);
   }
  } else {
   Scorer scorer = weight.scorer(reader);
   if (scorer != null) {
    scorer.score(collector);
   }
  }
...
}

由于BooleanWeight2被lucene-core给藏起来了,instanceof都不能用,只好丑陋一把用weight.getClass().getSimpleName().equals("BooleanWeight2")。
把BooleanWeight2替换为InaccurateBooleanWeight2后代码老是搜不到任何结果,经过千辛万苦地调试才发现BooleanWeight2初始化后并不算完,需要拿到sum、norm,然后normalize一把,有点bad smell。
接着从InaccurateBooleanWeight2里拿到InaccurateBooleanScorer2,调用getInaccurateTopAggregation搜一把,这里ascending并没有发挥作用,原因相当复杂,隐士引入ascending的本意是调整lucene扫描索引的方式,docID小->大或docID大->小,后来调整了建索引的方式就不需要这个了,所以隐士只是留这个接口以后用,万一以后lucene-core支持双向扫描索引即可启用。
2、InaccurateHits
InaccurateIndexSearcher里面调用search其实是调用new InaccurateHits(this, query, null, sort, ascending)。getMoreDocs会反向调用新写的search方法。
上代码:
...
TopDocs topDocs = (sort == null) ? searcher.search(weight, filter, n,
    ascending) : searcher
    .search(weight, filter, n, sort, ascending);
  length = topDocs.totalHits;
  InaccurateResultAggregation inaccurateResultAggregation = searcher
    .getInaccurateResultAggregation();
  if (inaccurateResultAggregation == null) {
   totalLength = length;
  } else {
   accurate = inaccurateResultAggregation.isAccurate();
   if (inaccurateResultAggregation.isAccurate()) {
    totalLength = inaccurateResultAggregation
      .getNumberOfRecordsFound();
   } else {
    int maxDocID = searcher.maxDoc();
    totalLength = 1000 * ((int) Math
      .ceil((0.001
        * maxDocID
        / (inaccurateResultAggregation.getLastDocID() + 1) * inaccurateResultAggregation
        .getNumberOfRecordsFetched()))); // guessing how many records there are
    }
  }
...

代码没什么特别的,除了一个猜测记录总数的算法。lucene从docID小向大的扫,由于上回说了扫到一半会跳出来,那么由最后扫到的lastDocID和maxDocID的比例可以猜测总共有多少条记录,虽然不是很准,但是数量级的精度是可以保证的,反正一般用户只能看到前1000条记录,具体有多少对用户来说不过是过眼云烟。
3、InaccurateBooleanWeight2
InaccurateBooleanWeight2没什么好说的,就是个拿到InaccurateBooleanScorer2的跳板。
4、InaccurateBooleanScorer2
InaccurateBooleanScorer2的代码均来自BooleanScorer2,由于BooleanScorer2从设计上来说并不准备被继承,隐士只好另起炉灶,bad smell啊。隐士没有修改任何从BooleanScorer2过来的代码,只加了getMaxNumberOfDocs、getInaccurateTopAggregation、getAccurateBottomAggregation。getInaccurateTopAggregation是扫描到maxNumberOfDocs后立即跳出来,所以结果会有所不准,getAccurateBottomAggregation总是保留最后maxNumberOfDocs个结果,结果也会有所不准,但是统计值是准的,因为每次都走完了所有索引。由两者差异可知getAccurateBottomAggregation性能会差一点,准确性和性能不可兼得啊。
 public InaccurateResultAggregation getInaccurateTopAggregation(
   HitCollector hc, boolean ascending) throws IOException {
  // DeltaTime dt = new DeltaTime();
  if (countingSumScorer == null) {
   initCountingSumScorer();
  }
  int lastDocID = 0;
  boolean reachedTheEnd = true;
  int numberOfRecordsFetched = 0;
  while (countingSumScorer.next()) {
   lastDocID = countingSumScorer.doc();
   float score = score();
   hc.collect(lastDocID, score);
   numberOfRecordsFetched++;
   if (numberOfRecordsFetched >= maxNumberOfDocs) {
    reachedTheEnd = !countingSumScorer.next();
    break;
   }
  }
  // System.out.println(dt.getTimeElasped());
  /*
   * This method might cast the rest away. So it might be inaccurate.
   */
  return new InaccurateResultAggregation(lastDocID, ascending,
    reachedTheEnd, numberOfRecordsFetched, numberOfRecordsFetched);
 }

 public InaccurateResultAggregation getAccurateBottomAggregation(
   HitCollector hc, boolean ascending) throws IOException {
  // DeltaTime dt = new DeltaTime();
  if (countingSumScorer == null) {
   initCountingSumScorer();
  }
  LinkedList<ResultNode> resultNodes = new LinkedList<ResultNode>();
  boolean isFull = false;
  int lastDocID = 0;
  int index = 0;
  int numberOfRecordsFound = 0;
  while (countingSumScorer.next()) {
   lastDocID = countingSumScorer.doc();
   float score = score();
   resultNodes.add(new ResultNode(lastDocID, score));
   if (isFull) {
    resultNodes.removeFirst();
   }
   index++;
   numberOfRecordsFound++;
   if (index >= maxNumberOfDocs) {
    isFull = true;
    index = 0;
    // break;
   }
  }
  for (ResultNode resultNode : resultNodes) {
   hc.collect(resultNode.getDoc(), resultNode.getScore());
  }
  // System.out.println(dt.getTimeElasped());

  /*
   * Since this method runs full scan against all matched docs, it's
   * accurate at all.
   */
  return new InaccurateResultAggregation(lastDocID, ascending, true,
    resultNodes.size(), numberOfRecordsFound);
 }


九、总结
代码已经打包上传了,有隐士写的简略注释,调用方式写在readme.txt里面,只需要替换几行代码即可。
总的来说只要
1、将Searcher searcher = new IndexSearcher(reader);替换为InaccurateIndexSearcher searcher = new InaccurateIndexSearcher(reader, 5000);
2、将Hits hits = searcher.search(query);替换为InaccurateHits hits = searcher.search(query, sort, ascending);
就行了。欢迎大家试用,如果有什么改进,请务必把改进后的代码也开源给大家,互相学习,互相促进。
由于代码里面有几处有bad smell,隐士实在没脸去lucene开发组那里喊一嗓子。
分享到:
评论
3 楼 bluepoint 2007-09-25  
lucene 2.2
单个词 搜索时(如:中国): 好像默认:TermQuery 那么 weight.getClass().getSimpleName().equals("BooleanWeight")
不成立,就用不上了,有啥办法处理?

多个词 搜索时(如:中国 上海):则可以使用.
2 楼 regedit 2007-07-06  
老大,如何调整lucene扫描索引的方式???
我想改为从大ID开始扫。。。
1 楼 caocao 2007-07-06  
已经升级到2.2了,在2.2里面,用这个修改的包不会有任何效果,因为BooleanWeight2已经没有了,现在只剩下BooleanWeight,只要把weight.getClass().getSimpleName().equals("BooleanWeight2")改成weight.getClass().getSimpleName().equals("BooleanWeight")即可。

顺便鄙视一下IT168,转载我的文章不写明出处。链接如下:

http://tech.it168.com/j/2007-06-04/200706040903078.shtml

http://tech.it168.com/j/2007-06-04/200706040939156.shtml

相关推荐

    lucene的封装和性能优化

    Lucene是一个高性能、全文本搜索库,它为开发者提供了在应用程序中实现全文检索的功能。然而,为了更好地适应实际项目需求,通常需要对其进行封装,以便于管理和提升性能。本文将深入探讨Lucene的封装方法以及如何...

    lucene3.6 搜索例子

    4. 结果集获取:使用TopDocs类来获取搜索结果,它包含了匹配文档的数量以及按评分排序的文档集合。 四、高级特性 1. 断点续搜:Lucene 3.6支持断点续搜,即在搜索过程中可以暂停并保存状态,之后继续搜索,这对于...

    Lucene5学习之拼音搜索

    本文将围绕“Lucene5学习之拼音搜索”这一主题,详细介绍其拼音搜索的实现原理和实际应用。 首先,我们需要理解拼音搜索的重要性。在中文环境中,由于汉字的复杂性,用户往往习惯于通过输入词语的拼音来寻找信息。...

    lucene查询结果集分页代码

    在lucene搜索分页过程中,可以有两种方式 一种是将搜索结果集直接放到session中,但是假如结果集非常大,同时又存在大并发访问的时候,很可能造成服务器的内存不足,而使服务器宕机 还有一种是每次都重新进行搜索,这样...

    Lucene与SSH2搜索功能

    "Lucene与SSH2搜索功能"的主题聚焦于如何在Java Web开发环境中利用Apache Lucene库来构建强大的搜索功能,并结合Struts2、Spring和Hibernate(简称SSH2)这三大框架进行整合。下面我们将深入探讨这些技术及其相互...

    lucene站内搜索

    Lucene是一个高性能、全文本搜索库,由Apache软件基金会开发,被广泛应用于各种搜索引擎和站内搜索解决方案中。它提供了丰富的文本分析、索引和搜索功能,使得开发者能够轻松地在自己的应用程序中实现复杂的全文检索...

    SpringBoot+Lucene搜索结果高亮显示Demo

    **SpringBoot+Lucene搜索结果高亮显示** 在现代Web应用程序中,强大的全文搜索引擎功能是不可或缺的,而Apache Lucene正是这样一个高效的、可扩展的开源全文检索库。在这个SpringBoot+Lucene的Demo中,我们将深入...

    Lucene全文搜索_LuceneJava全文搜索_

    索引过程就是将这些文档和字段转化为可以快速搜索的数据结构,而搜索则是基于用户输入的查询词,通过索引来查找相关文档。 Lucene的索引过程主要包括以下步骤: 1. **创建索引**:开发者需要将待搜索的数据(例如,...

    Java搜索引擎 Lucene

    4. **搜索索引**:通过Query对象定义搜索条件,使用Searcher对象执行搜索,并获取结果集。 5. **排序和评分**:Lucene提供TF-IDF等算法对搜索结果进行评分,可以根据评分进行排序。 6. **结果展示**:将搜索结果转换...

    lucene搜索引擎项目

    这个名为“lucene搜索引擎项目”的资源,旨在帮助用户更好地理解和应用Lucene来构建自己的搜索引擎。下面将详细探讨Lucene的核心概念和关键功能,以及如何利用这些特性来实现一个实际的搜索引擎。 1. **Lucene基础*...

    Lucene时间区间搜索

    总之,Lucene在C#中的时间区间搜索是通过构建和执行RangeQuery来实现的,这涉及到索引构建、查询解析、时间值的转换和比较等多个环节。合理地利用这些技术,可以有效地提升数据检索的效率和准确性。在实际应用中,还...

    lucene in action 2ed Edition

    《Lucene in Action 2nd Edition》是一本深入探讨Apache Lucene搜索引擎库的权威书籍,由Manning出版社在2010年发行。这本书详细介绍了如何利用Java编程语言来构建高性能、可扩展的全文检索应用。Lucene是Apache软件...

    lucene 资料全集

    所提供的文档资源,如《Lucene学习总结之一》、《传智播客Lucene3.0课程》、《JAVA_Lucene_in_Action教程完整版》以及《Lucene_in_Action(中文版)》,都是深入了解 Lucene 的宝贵资料,建议结合这些材料进行系统...

    一步一步跟我学习lucene(12)---lucene搜索之分组处理group查询

    在"一步一步跟我学习lucene(12)---lucene搜索之分组处理group查询"中,我们将重点关注如何利用Lucene实现这一高级搜索功能。 首先,Lucene是一个开源全文搜索引擎库,它为Java开发者提供了构建高效、可扩展的搜索...

    springmvc集成lucene全文搜索

    本篇文章将深入探讨如何在Spring MVC项目中集成Lucene进行全文搜索,以提升用户体验。 首先,我们需要理解Spring MVC和Lucene的基本概念。Spring MVC是一种基于模型-视图-控制器(MVC)架构模式的轻量级Web框架,它...

    lucene4.10.3的api的chm合集

    通过深入学习和利用这些API,开发者可以构建出功能强大、性能优异的全文搜索引擎。虽然缺失了“fact”的API,但这并不影响我们理解和利用Lucene的核心功能,为各种搜索应用场景打造定制化的解决方案。

    Weblucene 站内搜索

    你可以根据具体需求,学习并应用这些特性来提升搜索体验。 **5. 维护与升级** 为了保证Weblucene的稳定性和安全性,你需要定期检查更新,修复可能出现的问题,并根据新的版本特性进行升级。同时,监控搜索性能,...

    Lucene in Action 2nd Edition

    《Lucene in Action 2nd Edition》是关于Apache Lucene搜索引擎库的一本权威指南,由Manning出版社出版,于2010年6月推出了MEAP(Manning Early Access Program)新版。这本书深入浅出地介绍了如何利用Lucene进行...

    lucene实现企业产品检索

    在本文中,我们将深入探讨如何使用Lucene来实现一个类似当当网的企业产品检索系统,特别关注如何结合庖丁解牛分词器提升搜索体验。 首先,我们需要理解Lucene的基本工作原理。Lucene的核心是建立索引,将原始文本...

Global site tag (gtag.js) - Google Analytics