这里使用两个版本我一个是Lucene35 ,另外一个版本是一个Lucene46
Lucene35就一个jar包,到了Lucene46中就分成了7个jar包了。
第一个Lucene35
具体步骤: 创建索引的步骤
1、创建目录
2、创建IndexWriter
3、创建Docment对象
4、为Document添加Field
5、通过Indexwriter添加文档到索引中
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>3.5.0</version>
</dependency>
创建索引
package com.lk;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by LK on 2016/12/16.
*/
public class HelloLucene {
/*建立索引*/
public void index(){
//2创建IndexWriter
IndexWriter writer=null;
try {
//1创建Directory
// Directory directory= new RAMDirectory();//建立内存中
Directory directory = FSDirectory.open(new File("d:/lucene/index01")); //建立到硬盘上
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
writer=new IndexWriter(directory,iwc);
//3创建docment对象(相当于表中的一条记录)
Document document=null;
//4为Document添加Field
File f = new File("D:/lucene/example");
for(File file:f.listFiles()){
document = new Document();
document.add(new Field("content",new FileReader(file)));
document.add(new Field("filename",file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));
document.add(new Field("path",file.getAbsolutePath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
//5 通过IndexWriter添加文档到索引中
writer.addDocument(document);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(writer!=null) try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
第三步进行测试
package com.lk;
import org.junit.Test;
/**
* Created by LK on 2016/12/17.
*/
public class TestLucene {
@Test
public void testIndex(){
HelloLucene h1= new HelloLucene();
h1.index();
}
}
得到的目录是这样的: