这段时间考虑lucene的分组统计问题,网上查了不少文档,都没有给出效率比较高的解决方案。可以使用HitCollector对每个查询出来的document进行遍历,读取要分组的字段进行统计,但这样效率太低。以下是lucene API中对HitCollector的说明:
Note: This is called in an inner search loop. For good search performance, implementations of this method should not call Searcher.doc(int) or IndexReader.document(int) on every document number encountered. Doing so can slow searches by an order of magnitude or more.
所以现在要考虑的是不调用Searcher.doc(int) or IndexReader.document(int)这两个方法,就能获得要分组字段的值。由于lucene支持排序,是否可以将分组字段作为排序字段,然后直接读取出来进行分组呢?查询Lucene的javadoc文档,IndexSearcher提供了这个api
public TopFieldDocs search(Weight weight,Filter filter,int nDocs,Sort sort) throws IOException
调用这个方法可以获得排序字段的值,这样就可以进行分类统计了。代码如下:
searcher = new IndexSearcher(indexHome+"/"+indexDir);
TopFieldDocs docs=searcher.search(query, filter, topNum, sort);
//docs.scoreDocs数组对应查出的文档,仅包括排序字段的值
for(int i=0;i<docs.scoreDocs.length;i++){
FieldDoc fieldDoc = (FieldDoc) docs.scoreDocs[i];
//fieldDoc.fields数组对应每个排序字段
for (int j = 0; j < fieldDoc.fields.length; j++) {
String sortValue=fieldDoc.fields[j].toString();
result[j].addValue(sortValue);
}
Note: This is called in an inner search loop. For good search performance, implementations of this method should not call Searcher.doc(int) or IndexReader.document(int) on every document number encountered. Doing so can slow searches by an order of magnitude or more.
所以现在要考虑的是不调用Searcher.doc(int) or IndexReader.document(int)这两个方法,就能获得要分组字段的值。由于lucene支持排序,是否可以将分组字段作为排序字段,然后直接读取出来进行分组呢?查询Lucene的javadoc文档,IndexSearcher提供了这个api
public TopFieldDocs search(Weight weight,Filter filter,int nDocs,Sort sort) throws IOException
调用这个方法可以获得排序字段的值,这样就可以进行分类统计了。代码如下:
searcher = new IndexSearcher(indexHome+"/"+indexDir);
TopFieldDocs docs=searcher.search(query, filter, topNum, sort);
//docs.scoreDocs数组对应查出的文档,仅包括排序字段的值
for(int i=0;i<docs.scoreDocs.length;i++){
FieldDoc fieldDoc = (FieldDoc) docs.scoreDocs[i];
//fieldDoc.fields数组对应每个排序字段
for (int j = 0; j < fieldDoc.fields.length; j++) {
String sortValue=fieldDoc.fields[j].toString();
result[j].addValue(sortValue);
}