public void createIndex() throws IOException {
// 第一步采集数据:(jdbc采集数据)
BookDao dao = new BookDaoImpl();
List<Book> queryBookList = dao.queryBookList();
// 将数据采集放到docment对象中
Document doc = null;
List<Document> docList = new ArrayList<>();
for (Book book : queryBookList) {
// 根据需求创建不同的field Store是是否存储
doc = new Document();
Field id = new TextField("id", book.getId().toString(), Store.YES);
Field name = new TextField("name", book.getName(), Store.YES);
Field price = new TextField("price", book.getPrice().toString(), Store.YES);
Field pic = new TextField("pic", book.getPic(), Store.YES);
Field desc = new TextField("description", book.getDescription(), Store.YES);
// 将field域,添加到文档对象中
doc.add(id);
doc.add(name);
doc.add(price);
doc.add(pic);
doc.add(desc);
docList.add(doc);
}
//创建一个indexWriter对象(通过它反向推理出需要的条件)
//先构造一个directory 指定索引库的位置,一般使用文件系统的目录。
FSDirectory directory = FSDirectory.open(new File("G:\\index01"));
//创建一个分词器 对文档中的Field域进行分词
Analyzer analyzer = new StandardAnalyzer();//标准分词器
IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
IndexWriter writer = new IndexWriter(directory,config);
//创建索引
for (Document document : docList) {
writer.addDocument(document);
}
//关闭资源
writer.close();
}