packagecom.pomelo.search;importcom.pomelo.dao.BookDao;importcom.pomelo.dao.impl.BookDaoImpl;importcom.pomelo.domain.Book;importorg.apache.lucene.analysis.Analyzer;importorg.apache.lucene.document.Document;importorg.apache.lucene.document.Field.Store;importorg.apache.lucene.document.TextField;importorg.apache.lucene.index.IndexWriter;importorg.apache.lucene.index.IndexWriterConfig;importorg.apache.lucene.store.Directory;importorg.apache.lucene.store.FSDirectory;importorg.apache.lucene.util.Version;importorg.junit.Test;importorg.wltea.analyzer.lucene.IKAnalyzer;importjava.io.File;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;//2. 创建索引
public classIndexManagerDemo {
@Testpublic void createIndex() throwsIOException {//1. 采集文档数据
BookDao bookDao = newBookDaoImpl();
List bookList =bookDao.findAll();//2. 创建文档对象
List documentList = new ArrayList<>();for(Book book : bookList) {
Document document= newDocument();/*** IntField整型类型域,TextField文本类型域,FloatField浮点型类型域
* 参数1:域名--对应数据库中字段名
* 参数2:域值
* 参数3:是否存储--是否需要将该域对应的值存储到文档中*/document.add(new TextField("bookId", book.getId() + "", Store.YES));
document.add(new TextField("bookName", book.getBookName(), Store.YES));
document.add(new TextField("bookPrice", book.getPrice() + "", Store.YES));
document.add(new TextField("bookPic", book.getPic(), Store.YES));
document.add(new TextField("bookDesc", book.getBookDesc(), Store.YES));
documentList.add(document);
}//3. 创建分词器
Analyzer analyzer = newIKAnalyzer();//4、创建文档索引配置对象
IndexWriterConfig indexWriterConfig = newIndexWriterConfig(Version.LUCENE_4_10_3, analyzer);//5、创建存放索引目录Directory,指定索引存放路径
File file = new File("C:\\tmp\\lucene\\book1");
Directory directory=FSDirectory.open(file);//6、创建索引编写器
IndexWriter indexWriter = newIndexWriter(directory, indexWriterConfig);//7、利用索引编写器写入文档到索引目录
for(Document document : documentList) {//把文档对象写入到索引库中
indexWriter.addDocument(document);
}//8. 释放资源
indexWriter.close();
}
}