利用Lucene的IndexWriter建立索引(详解)
/* * 建立索引,然后把建立后的文档添加到索引中去 * 提示先使用Document和Field把Field加入到Document中去, * 接着把Document建立成为一个索引 * */ package comThree;
import java.io.IOException;
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;
public class BookIndex{
//创建索引的目录 private String INDEX_PATH = "E:\Lucene项目\索引目录"; Document bookdoc1 = null; public BookIndex(){
bookdoc1 = new Document(); System.out.println("开始创建书的Field字段---------->>>>");
//书的编号 Field bookNo = new Field("booknumber", "FB309663004", Field.Store.YES, Field.Index.TOKENIZED); //书名 Field bookName = new Field("bookName", "钢铁是怎样炼成的", Field.Store.YES, Field.Index.TOKENIZED );
//书的作者 Field anthor = new Field("author", "匿名", Field.Store.YES, Field.Index.TOKENIZED);
//出版日期 Field publishdate = new Field("publishdate", "出版日期", Field.Store.YES, Field.Index.NO);
//描述 Field bookabstract = new Field("abstract", "钢铁是怎样炼成的", Field.Store.NO, Field.Index.TOKENIZED);
//价格 Field price = new Field("price", "25.00", Field.Store.YES, Field.Index.NO);
System.out.println("完成创建书的Field字段---------->>>>");
System.out.println("开始将书的字段放入到文档中-------------》》"); //把Field加入Document bookdoc1.add(bookNo); bookdoc1.add(bookName); bookdoc1.add(bookabstract); bookdoc1.add(publishdate); bookdoc1.add(price);
System.out.println("完成书的字段放入到文档中------------->>>>>");
try{
System.out.println("开始创建索引-------------------->>>>"); //创建索引实例 IndexWriter writer = new IndexWriter(INDEX_PATH, new StandardAnalyzer());
//构建一个indexWriter的实例 writer.addDocument(bookdoc1);
//在这里必须要关闭,否则会出现异常,例如数据没有写入完整。 writer.close(); System.out.println("完成索引的创建并且存储完毕, 索引的存放位置在:" INDEX_PATH); }catch(IOException e){ e.printStackTrace(); } }
public static void main(String[] args){ BookIndex BI = new BookIndex(); }
}