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

来源:互联网 发布:学java看什么书好 编辑:程序博客网 时间:2024/06/11 02:26

转自:

http://www.javaeye.com/topic/78884

http://www.javaeye.com/topic/80073

 

一、缘起
Lucene在索引文件上G之后的搜索性能下降很严重,随便跑个搜索就要上0.x秒。如果是单线程搜索那么性能尚可,总可以在0.x秒返回结果,如果是Web式的多线程访问,由于Lucene的内部机制导致数据被大量载入内存,用完后立即丢弃,随之引起JVM频繁GC,性能极其低下,1-10秒的长连接比比皆是。这也是世人为之诟病的Lucene应用瓶颈问题,那么是否有解决方法呢?

二、思路
我们来观察Google, Baidu的搜索,有一个总体的感觉就是搜索结果多的关键词耗时比较少,结果少的关键词耗时反而多,且结果多的时候会说“约******个结果”。隐士猜测Google, Baidu的算法是找到前n个结果后停止扫描索引,根据前n个结果来推断总共有多少个结果,此猜想可由Google, Baidu翻页限制而得到部分验证。
再看Lucene,其Hits.length()返回的总是精确的结果,如果可以让Lucene也返回模糊的结果,那么索引文件就算是10G也可以轻松应对了。

三、探索
隐士带着这个问题访名山、觅高人,可惜没有找到前人的成果,可能是隐士走的路不够勤,如有类似的解决方案,隐士不吝赐教。
无奈之下,隐士详细研究了Lucene 2.1.0源码,准备重新发明轮子。
一般来说大多数搜索应用中的Query都会落在BooleanQuery上,隐士就拿它开刀。一路看来,BooleanScorer2里的一个method吸引了隐士,代码如下:

Java代码 复制代码
  1. public void score(HitCollector hc) throws IOException {   
  2.   if (countingSumScorer == null) {   
  3.     initCountingSumScorer();   
  4.   }   
  5.   while (countingSumScorer.next()) {   
  6.     hc.collect(countingSumScorer.doc(), score());   
  7.   }   
  8. }  



在while循环里嵌入写日志代码可证结果集有多大,此处就循环了多少次。countingSumScorer.next()的意思是找到下一个符合boolean规则的document,找到后放入HitCollector,这HitCollector后面会换个马甲放在大家熟悉的Hits里面。
如果可以在这个while循环里嵌一个break,到一定数量就break出来,性能提升将相当明显。这个代码相当简单,果然大幅提高了性能,带来的副作用是结果不太准,这个可以通过调整业务模型、逻辑来修正。毕竟这是一条提升Lucene性能的有效方法。
细细想来,正是由于这个break会导致结果集大的关键词提前出来,搜索时间少,结果集小的关键词不可避免会走完整个索引,相应的搜索时间会长一点。

四、效果
由于具体嵌入代码的过程极其繁琐,隐士将在第二回详细讲解。这第一回先来个Big picture。
历尽千辛万苦,隐士终于搞定了这套程序,效果可以从隐士做的视频搜索http://so.mdbchina.com/video/%E7%BE%8E%E5%A5%B3看出。
这个关键词“美女”可以找到18万个视频,平均0.5秒返回结果,现在用上了新算法,只要0.06x秒返回结果,而且返回结果足够好了,估算的8.5万个结果虽然离18万有很大差距,不过由于是估算的,差2-3倍应属可以接受的。
由算法的特性可知,while里面的hc.collect总可以在常量时间内完成,循环次数又是<=常量,该算法的时间复杂度只和BooleanQuery的复杂程度相关,和索引文件大小以及命中的Document在索引文件内的分布密度没有关系,因为BooleanQuery的复杂程度决定了countingSumScorer.next()需要经过多少次判断、多少次读取索引文件,countingSumScorer.next()正是整个算法中耗时不定的部分。
现在这个视频搜索的索引文件接近3G,热门关键词可以在0.0x秒返回结果,隐士相信即使以后索引文件上到10G,依然可以在0.0x秒返回结果。

(注:这个视频搜索实际使用效果会打折扣,因为后台索引也在这台机器上,以后会分服务器,现在暂时在一起。)

呵呵,不知不觉写了那么多,下一回(http://www.javaeye.com/topic/80073)将上代码,敬请关注。

 

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

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

七、文件

Java代码 复制代码
  1. org.apache.lucene.search   
  2.     InaccurateBooleanScorer2.java // BooleanScorer2的替代品   
  3.     InaccurateBooleanWeight2.java // BooleanWeight2的替代品   
  4.     InaccurateHit.java // Hit的替代品   
  5.     InaccurateHitIterator.java // HitIterator的替代品   
  6.     InaccurateHits.java // Hits的替代品   
  7.     InaccurateIndexSearcher.java // IndexSearcher的替代品   
  8. org.apache.lucene.util   
  9.     InaccurateResultAggregation.java // 放搜索统计信息的value object  



八、实战
1、InaccurateIndexSearcher
InaccurateIndexSearcher extends IndexSearcher,结构很简单,增加了两个成员变量:maxNumberOfDocs和inaccurateResultAggregation,以及几个methods。
丑陋的部分来了:

Java代码 复制代码
  1. public void search(Weight weight, Filter filter, final HitCollector results, boolean ascending) throws IOException {   
  2. ...   
  3.   if (weight.getClass().getSimpleName().equals("BooleanWeight2")) { // hook BooleanWeight2   
  4.    InaccurateBooleanWeight2 inaccurateBooleanWeight2 = new InaccurateBooleanWeight2(   
  5.      this, weight.getQuery());   
  6.    float sum = inaccurateBooleanWeight2.sumOfSquaredWeights();   
  7.    float norm = this.getSimilarity().queryNorm(sum);   
  8.    inaccurateBooleanWeight2.normalize(norm); // bad smell   
  9.    InaccurateBooleanScorer2 inaccurateBooleanScorer2 = inaccurateBooleanWeight2   
  10.      .getInaccurateBooleanScorer2(reader, maxNumberOfDocs);   
  11.    if (inaccurateBooleanScorer2 != null) {   
  12.     inaccurateResultAggregation = inaccurateBooleanScorer2   
  13.       .getInaccurateTopAggregation(collector, ascending);   
  14.    }   
  15.   } else {   
  16.    Scorer scorer = weight.scorer(reader);   
  17.    if (scorer != null) {   
  18.     scorer.score(collector);   
  19.    }   
  20.   }   
  21. ...   
  22. }  


由于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方法。
上代码:

Java代码 复制代码
  1. ...   
  2. TopDocs topDocs = (sort == null) ? searcher.search(weight, filter, n,   
  3.     ascending) : searcher   
  4.     .search(weight, filter, n, sort, ascending);   
  5.   length = topDocs.totalHits;   
  6.   InaccurateResultAggregation inaccurateResultAggregation = searcher   
  7.     .getInaccurateResultAggregation();   
  8.   if (inaccurateResultAggregation == null) {   
  9.    totalLength = length;   
  10.   } else {   
  11.    accurate = inaccurateResultAggregation.isAccurate();   
  12.    if (inaccurateResultAggregation.isAccurate()) {   
  13.     totalLength = inaccurateResultAggregation   
  14.       .getNumberOfRecordsFound();   
  15.    } else {   
  16.     int maxDocID = searcher.maxDoc();   
  17.     totalLength = 1000 * ((int) Math   
  18.       .ceil((0.001  
  19.         * maxDocID   
  20.         / (inaccurateResultAggregation.getLastDocID() + 1) * inaccurateResultAggregation   
  21.         .getNumberOfRecordsFetched()))); // guessing how many records there are   
  22.     }   
  23.   }   
  24. ...  


代码没什么特别的,除了一个猜测记录总数的算法。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性能会差一点,准确性和性能不可兼得啊。

Java代码 复制代码
  1. public InaccurateResultAggregation getInaccurateTopAggregation(   
  2.   HitCollector hc, boolean ascending) throws IOException {   
  3.  // DeltaTime dt = new DeltaTime();   
  4.  if (countingSumScorer == null) {   
  5.   initCountingSumScorer();   
  6.  }   
  7.  int lastDocID = 0;   
  8.  boolean reachedTheEnd = true;   
  9.  int numberOfRecordsFetched = 0;   
  10.  while (countingSumScorer.next()) {   
  11.   lastDocID = countingSumScorer.doc();   
  12.   float score = score();   
  13.   hc.collect(lastDocID, score);   
  14.   numberOfRecordsFetched++;   
  15.   if (numberOfRecordsFetched >= maxNumberOfDocs) {   
  16.    reachedTheEnd = !countingSumScorer.next();   
  17.    break;   
  18.   }   
  19.  }   
  20.  // System.out.println(dt.getTimeElasped());   
  21.  /*  
  22.   * This method might cast the rest away. So it might be inaccurate.  
  23.   */  
  24.  return new InaccurateResultAggregation(lastDocID, ascending,   
  25.    reachedTheEnd, numberOfRecordsFetched, numberOfRecordsFetched);   
  26. }   
  27.   
  28. public InaccurateResultAggregation getAccurateBottomAggregation(   
  29.   HitCollector hc, boolean ascending) throws IOException {   
  30.  // DeltaTime dt = new DeltaTime();   
  31.  if (countingSumScorer == null) {   
  32.   initCountingSumScorer();   
  33.  }   
  34.  LinkedList<ResultNode> resultNodes = new LinkedList<ResultNode>();   
  35.  boolean isFull = false;   
  36.  int lastDocID = 0;   
  37.  int index = 0;   
  38.  int numberOfRecordsFound = 0;   
  39.  while (countingSumScorer.next()) {   
  40.   lastDocID = countingSumScorer.doc();   
  41.   float score = score();   
  42.   resultNodes.add(new ResultNode(lastDocID, score));   
  43.   if (isFull) {   
  44.    resultNodes.removeFirst();   
  45.   }   
  46.   index++;   
  47.   numberOfRecordsFound++;   
  48.   if (index >= maxNumberOfDocs) {   
  49.    isFull = true;   
  50.    index = 0;   
  51.    // break;   
  52.   }   
  53.  }   
  54.  for (ResultNode resultNode : resultNodes) {   
  55.   hc.collect(resultNode.getDoc(), resultNode.getScore());   
  56.  }   
  57.  // System.out.println(dt.getTimeElasped());   
  58.   
  59.  /*  
  60.   * Since this method runs full scan against all matched docs, it's  
  61.   * accurate at all.  
  62.   */  
  63.  return new InaccurateResultAggregation(lastDocID, ascending, true,   
  64.    resultNodes.size(), numberOfRecordsFound);   
  65. }  



九、总结
代码已经打包上传了,有隐士写的简略注释,调用方式写在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开发组那里喊一嗓子。

原创粉丝点击