lucene3.5学習ノート01

2938 ワード

最近この方面の知識を見て、初心者はいっしょに分かち合います


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