lucene 入门
2018-07-20 来源:open-open
public void index() { //1.创建Directory Directory directory = null; Analyzer analyzer = null; IndexWriterConfig iwc = null; IndexWriter writer = null ; try { //Directory directory = new RAMDirectory();//建立在内存中 directory = FSDirectory.open(Paths.get("L:/java/study/lucenc1/src/main/resources/example/index01"));//建立在硬盘上 //2. 创建IndexWriter analyzer = new StandardAnalyzer(); iwc = new IndexWriterConfig(analyzer); writer = new IndexWriter(directory, iwc); //3.创建Document对象 Document d = null; //4. 位Document 添加Field File f= new File("L:/java/study/lucenc1/src/main/resources/example/lucene"); for(File file : f.listFiles()){ d = new Document(); d.add(new TextField("content",new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)))); d.add(new StringField("filename", file.getName(),Field.Store.YES)); d.add(new StringField("path", file.toString(), Field.Store.YES) ); writer.addDocument(d); } } catch (IOException e) { e.printStackTrace(); } finally{ if(writer != null){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public void searcher(){ Directory directory = null; IndexReader reader = null; IndexSearcher searcher = null; Analyzer analyzer = null; QueryParser parser = null; try { //1.创建Directory directory = FSDirectory.open(Paths.get("L:/java/study/lucenc1/src/main/resources/example/index01")); //2.创建IndexReader reader = DirectoryReader.open(directory); //3.根据IndexReader创建IndexSearcher searcher = new IndexSearcher(reader); //4.创建搜索的Query //创建parser来确定要搜索文件的内容,第二个参数表示搜索的域 analyzer = new StandardAnalyzer(); parser = new QueryParser("content", analyzer); //创建query,表示搜索域为content中包含java的文档 Query query = parser.parse("linux"); //5.根据searcher搜索并且返回TopDoces TopDocs tds = searcher.search(query, 10);//10 搜索的条数 //6.根据topDocs获取scoreDoc对象 ScoreDoc[] sds = tds.scoreDocs; for(ScoreDoc sd : sds){ //7.根据searcher和scoreDoc对象获取具体的Document对象 Document d = searcher.doc(sd.doc); //8.根据Document对象获取需要的值 System.out.println(d.get("filename")+"["+d.get("path")+"]"); } //9.关闭reader } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } finally{ if(reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐