建立索引的步驟:
0.建立分詞器
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
1.建立Directory,索引存放的位置
Directory directory = FSDirectory.open(new File("E:/Lucene/demo"));
2.建立IndexWrite,索引寫入器
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,analyzer);
IndexWrite write = new IndexWriter(directory,iwc);
3.建立Document對象
Document doc = new Document();
4.給Document添加Field
doc.add(new Field("name",names[i],Store.YES,Index.ANALYZED)); --添加字元串
doc.add(new NumericField("attach",Store.YES,true).setIntValue(23)); --添加整數
doc.add(new NumericField("attach",Store.YES,true).setDoubleValue(2.5d)); --添加雙精度浮點
doc.add(new NumericField("attach",Store.YES,true).setFloatValue(3.6f)); --添加單精度浮點
doc.add(new NumericField("attach",Store.YES,true).setLongValue(44)); --添加長整型
doc.add(new NumericField("date",Store.YES,true).setLongValue(201254221)); --添加日期
doc.setBoost(2.5); --權重
5.添加文檔到索引
writer.addDocument(doc);
6.送出或者關閉IndexWrite寫入器(隻有這樣,索引才會正常建立)
writer.commit();
writer.close();
知識點
一、第0步驟的分詞器(可以自定義分詞器,重難點)
二、第1步驟建立索引檔案目錄(單例模式建立)
三、給Document添加域(不同資料類型的域值操作)
單例模式建立Directory、IndexReader、IndexSearcher代碼:
private static IndexReader reader;
private static Directory directory;
static{
try {
directory = FSDirectory.open(new File("E:/Lucene/demo"));
reader = IndexReader.open(directory);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Directory getDictionary(){
return directory;
}
public static IndexReader getIndexReader(){
return reader;
}
public static IndexSearcher getIndexSearcher(){
try {
if(reader != null){
reader = IndexReader.open(directory);
}else{
IndexReader ir = IndexReader.openIfChanged(reader);
if(ir != null){
reader.close();
reader = ir;
}
}
return new IndexSearcher(reader);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void closeSearcher(IndexSearcher searcher){
try {
if(searcher != null){
searcher.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeWrite(IndexWriter indexWriter){
try {
if(indexWriter != null){
indexWriter.close();
}
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}