首页 > 代码库 > lucene

lucene

public class Indexer {
    public void  index() throws IOException {
        //创建dicti
    //    Directory dir =  new RAMDirectory();
        Directory dir = FSDirectory.open(Paths.get("I:/testDemo/lucene/"));
        //indexWriter
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        IndexWriter writer=null;
        try {
            writer = new IndexWriter(dir, conf);
            File file = new File("I:/testDemo/data");
            for(File f : file.listFiles()){
                Document doc = new  Document();
                doc.add(new TextField("content", new FileReader(f)));
                doc.add(new TextField("name", f.getName(), Store.YES));
                doc.add(new TextField("path", f.getAbsolutePath(), Store.YES));
                writer.addDocument(doc);
            }
            
        } catch (Exception e) {
            
        }finally{
            try {
                if(writer!=null) writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    
    public void searcher() throws IOException, ParseException{
        Directory dir = FSDirectory.open(Paths.get("I:/testDemo/lucene/"));
        IndexReader reader=DirectoryReader.open(dir);
        IndexSearcher isearcher = new IndexSearcher(reader);
        Analyzer analyzer=new StandardAnalyzer(); // 标准分词器
        QueryParser parser=new QueryParser("content", analyzer);
        Query query=parser.parse("REPRODUCTION");
        long start=System.currentTimeMillis();
        TopDocs hits=isearcher.search(query, 10);
        long end=System.currentTimeMillis();
        System.out.println("匹配 "+"REPRODUCTION"+" ,总共花费"+(end-start)+"毫秒"+"查询到"+hits.totalHits+"个记录");
        for(ScoreDoc scoreDoc:hits.scoreDocs){
            Document doc=isearcher.doc(scoreDoc.doc);
            System.out.println(doc.get("path"));
        }
        reader.close();
    }
    
    public static void main(String[] args) {
        Indexer indexer = new Indexer();
        try {
            indexer.index();
            indexer.searcher();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 

lucene