1、创建索引
1 /**
2 * 建立索引
3 */
4 public void index(){
5 IndexWriter writer=null;
6 try {
7 //1.创建Directory
8 //Directory directory=new RAMDirectory();//建立在内存中
9 Directory directory=FSDirectory.open(new File("D:/lucene/lucene01"));//创建在硬盘上
10 //2.创建IndexWrite
11 IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_35,new StandardAnalyzer(Version.LUCENE_35));
12 writer=new IndexWriter(directory, iwc);
13 //3.创建Document对象
14 Document doc=null;
15 //4.为Document添加Field
16 File f=new File("D:/lucene/example");
17 for (File file:f.listFiles()) {
18 doc=new Document();
19 doc.add(new Field("content",new FileReader(file)));
20 doc.add(new Field("filename",file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));
21 doc.add(new Field("path",file.getAbsolutePath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
22 //5.通过Index Writer添加文档到索引中
23 writer.addDocument(doc);
24 }
25
26
27
28 } catch (IOException e) {
29 // TODO Auto-generated catch block
30 e.printStackTrace();
31 }finally{
32 if(writer!=null){
33 try {
34 writer.close();
35 } catch (IOException e) {
36 // TODO Auto-generated catch block
37 e.printStackTrace();
38 }
39 }
40 }
41
42 }
2、搜索
1 /***
2 * 搜索
3 */
4 public void searcher(){
5 try {
6 //1.创建Directory
7 Directory directory=FSDirectory.open(new File("D:/lucene/lucene01"));//创建在硬盘上
8 //2.创建IndexReader
9 IndexReader reader=IndexReader.open(directory);
10 //3.根据IndexReader创建IndexSearcher
11 IndexSearcher searcher=new IndexSearcher(reader);
12 //4.创建搜索的Query
13 //创建parser来确定要搜索文件的内容,第二个参数表示搜索的域
14 QueryParser parser=new QueryParser(Version.LUCENE_35, "content", new StandardAnalyzer(Version.LUCENE_35));
15 //创建query,表示搜索域为content中包含Java的文档
16 Query query=parser.parse("migrate");
17 //5.根据searcher搜索并且返回TopDocs
18 //10 搜索条数
19 TopDocs tds=searcher.search(query, 10);
20 //6.根据TopDocs获取ScoreDoc对象
21 ScoreDoc[] sds= tds.scoreDocs;
22 for (ScoreDoc sd : sds) {
23 //7.根据searcher和ScoreDoc对象获取具体的document对象
24 Document d=searcher.doc(sd.doc);
25 //8.根据Document对象获取需要的值
26 System.out.println(d.get("filename")+"["+d.get("path")+"]");
27 }
28
29
30 //9.关闭reader
31 reader.close();
32 } catch (CorruptIndexException e) {
33 // TODO Auto-generated catch block
34 e.printStackTrace();
35 } catch (IOException e) {
36 // TODO Auto-generated catch block
37 e.printStackTrace();
38 } catch (ParseException e) {
39 // TODO Auto-generated catch block
40 e.printStackTrace();
41 }
42 }
3、Junit测试
1 @Test
2 public void testIndex(){
3 HelloLucene hl=new HelloLucene();
4 hl.index();
5 }
6
7 @Test
8 public void testSearch(){
9 HelloLucene hl=new HelloLucene();
10 hl.searcher();
11 }