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();
	}
	
	
	
}

你可能感兴趣的:(lucene3.5)