標籤:example log pen pdo tin api reader top failed
一、Lucene的基礎(2017-05-11 10:40:46)
1、Lucene的下載
API的下載:http://pan.baidu.com/s/1nvLTG0L
2、Lucene的使用
/** * 建立索引 */ public void index(){ IndexWriter writer = null; try { //1、建立Directory //Directory directory = new RAMDirectory();//建立在記憶體中 //建立在硬碟上 Directory directory = FSDirectory.open(new File("d:/import/studytool/Lucene/index01")); //2、建立IndexWriter IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)); writer = new IndexWriter(directory, iwc); //3、建立Document對象 Document doc = null; //4、為Document添加Field File f = new File("d:/import/studytool/Lucene/example"); for(File file : f.listFiles()){ doc = new Document(); doc.add(new Field("content", new FileReader(file))); doc.add(new Field("filename", file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED)); doc.add(new Field("path",file.getPath(),Field.Store.YES,Field.Index.NOT_ANALYZED)); //5、通過IndexWriter添加文檔到索引中 writer.addDocument(doc); } } catch (CorruptIndexException e) { e.printStackTrace(); } catch (LockObtainFailedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * 搜尋 */ public void searcher(){ try { //1、建立Directory Directory directory = FSDirectory.open(new File("d:/import/studytool/Lucene/index01")); //2、建立IndexReader IndexReader reader = IndexReader.open(directory); //3、根據IndexReader建立IndexSearcher IndexSearcher searcher = new IndexSearcher(reader); //4、建立搜尋的Query //建立parser來確定要搜尋檔案的內容,第二個參數表示搜尋的域 QueryParser parser = new QueryParser(Version.LUCENE_35, "content", new StandardAnalyzer(Version.LUCENE_35)); //建立query,表示搜尋域為content中包含come的文檔 Query query = parser.parse("come"); //5、根據Seacher搜尋並返回TopDocs TopDocs tds = searcher.search(query, 10); //6、根據TopDocs擷取ScoreDoc對象 ScoreDoc[] sds = tds.scoreDocs; for(ScoreDoc sd : sds){ //7、根據seacher和ScordDoc對象擷取具體的Document對象 Document d = searcher.doc(sd.doc); //8、根據Document對象擷取需要的值 System.out.println(d.get("filename")+"["+d.get("path")+"]"); } //9、關閉reader reader.close(); } catch (CorruptIndexException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
3、基本執行個體4、系統架構
Lucene的學習與總結(二)