lucene3.5 学习笔记01

最近在看这方面的知识,初学者一起分享


public class LuceneTest {

File filePath = new File("D:\\uploadfiles");
File indexPath = new File("D:\\luceneIndex");
//创建分词器
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
//建立索引的配置类,包含了一个解析器
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, analyzer).setOpenMode(OpenMode.CREATE);




public void indexMethod(IndexWriter writer, File file) throws Exception{
if(file.isDirectory()){
String[] files = file.list();
for(int i=0;i<files.length;i++){
indexMethod(writer,new File(file,files[i]));
}
}else{
FileInputStream fis = new FileInputStream(file);
Document doc = new Document();
doc.add(new Field("name",file.getName(),Store.YES,Index.ANALYZED));
// doc.add(new Field("content",new BufferedReader(new InputStreamReader(fis, "UTF-8"))));

doc.add(new Field("content",ToolUtilFile.fileToStringUtil(file),Store.YES,Index.ANALYZED));


doc.add(new Field("size",String.valueOf(file.length()),Store.YES,Index.ANALYZED_NO_NORMS));
doc.add(new Field("path",file.getAbsolutePath(),Store.YES,Index.ANALYZED_NO_NORMS));
writer.addDocument(doc);


}
}

public void searchMethod() throws Exception{
//获取查询
Directory directory = FSDirectory.open(indexPath);
IndexReader reader = IndexReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader);

//把要搜索的文本解析为Query
String queryString = "hello";
String[] fields = {"name","content"};

QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_35, fields, analyzer);
Query query = parser.parse(queryString);
TopDocs topDocs = searcher.search(query, null, 10000);//topDocs 类似集合
System.out.println("总共有【"+topDocs.totalHits+"】条匹配结果.");
//输出
for(ScoreDoc scoreDoc:topDocs.scoreDocs){
int docSn = scoreDoc.doc;//文档内部编号
Document doc = searcher.doc(docSn);//根据文档编号取出相应的文档
File2Document.printDocumentInfo(doc);//打印出文档信息

}
}




@Test
public void createIndex() throws Exception{
Directory dir = FSDirectory.open(indexPath);
IndexWriter writer = new IndexWriter(dir, iwc);
indexMethod(writer,filePath);
writer.close();
}

@Test
public void searchIndex() throws Exception{
searchMethod();
}



}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值