liuqiang5151

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  0 Posts :: 23 Stories :: 1 Comments :: 0 Trackbacks
终于清楚如何用读Lucene的索引 :-)。本文要介绍一下如何利用IndexReader获取信息。为什么要读索引呢?因为我需要实现这些功能:
(1) 统计term在整个collection中的文档频度(document frequency, DF);
(2) 统计term在整个collection中出现的词次(term frequency in whole collection);
(3) 统计term在某个文档中出现的频度(term frequency, TF);
(4) 列出term在某文档中出现的位置(position);
(5) 整个collection中文档的个数;

Lucene要加上新的功能,要获取关键词出现的频率,以前都是对Hits进行操作,但是hits只能获取相关的Document id 以及内容。
上网搜了一下,通过IndexReader直接操作索引文件。
public class Search {
    
public static void main(String[] args) throws CorruptIndexException, IOException{
        IndexSearcher is 
= new IndexSearcher("c:\\test");
        IndexReader ir 
= IndexReader.open("c:\\test");
        Term term 
= new Term("content","");
        Query query 
= new TermQuery(term);
        Hits hits 
= is.search(query);
        printFreq(ir,hits);
        
    }

    
private static void printFreq(IndexReader reader,Hits hits) throws CorruptIndexException, IOException{
        reader.numDocs();
        Term term 
= new Term("content","");
        TermPositions termPositions 
= reader.termPositions(term);
        
for(int i=0;i<hits.length()&&termPositions.next();i++){
            Document doc 
= hits.doc(i);
            System.out.println(
"'我'在"+"<<"+doc.get("title")+">>"+"里出现的"+"次数是:"+termPositions.freq());
            
for(int j=0;j<termPositions.freq();j++)
                System.out.println(
"出现位置:"+termPositions.nextPosition());
        }

    }

}


输出结果:
'我'在<<2.txt>>里出现的次数是:1
出现位置:1
'我'在<<3.txt>>里出现的次数是:3
出现位置:0
出现位置:5
出现位置:6
posted on 2007-10-15 17:54 刘强 阅读(647) 评论(0)  编辑  收藏 所属分类: Lucene

只有注册用户登录后才能发表评论。


网站导航: