public class Lucene {
//创建索引程序
@Test
public void createIndex() throws IOException{
//指定存储索引库位置
String path = "F:\\indexs";
//和索引库进行关联
FSDirectory d = FSDirectory.open(new File(path));
//创建分词器
Analyzer analyzer = new StandardAnalyzer();
//indexWriterConfig是对IndexWriter进行一些配置,lucene版本,最大缓存文档数
IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);
//使用indexWriter进行写入索引
IndexWriter indexWriter = new IndexWriter(d, conf);
//创建document,IndexWriter把文档对象写入到索引库
Document doc = new Document();
//模拟数据
//StringField:这个域不进行分词,Store.YES:表示存储document。
//Store.NO:表示不存储。
doc.add(new StringField("id", "1", Store.YES));
doc.add(new TextField("title", "Lucene基础教程", Store.YES));
doc.add(new TextField("content","Lucene是一套用于开发搜索引擎的一套javaAPI!", Store.YES));
//写入索引
indexWriter.addDocument(doc);
//提交
indexWriter.commit();
indexWriter.close();
}
}
主要对象有Directory指定索引库目录位置, 参数为路径;
Analyzer分词器(IKAnalyzer), 创建一个分词器;
IndexWriterConfig是对IndexWriter进行配置,并传入分词器
创建一个IndexWriter,写入索引的对象,参数为索引库关联对象, 配置文件 ;
创建Document对象加入域
写入索引