package com.lucene;
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;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
public class RamAndDiskIndex {
private static String path = "d:/index";
public static void main(String[] args) {
index();
search();
}
public static void index(){
try{
Directory ramDir = new RAMDirectory();
Directory diskDir = FSDirectory.getDirectory(path);
IndexWriter ramWriter = new IndexWriter(ramDir,new StandardAnalyzer(),true);
IndexWriter diskWriter = new IndexWriter(diskDir,new StandardAnalyzer(),true);
//新增一条数据到内存索引中,然后再由内存索引加入到磁盘索引中去
Document doc = new Document();
doc.add(new Field("id","123456",Field.Store.YES,Field.Index.TOKENIZED));
doc.add(new Field("value","hello world",Field.Store.YES,Field.Index.TOKENIZED));
//添加到内存
ramWriter.addDocument(doc);
//关闭ram的IndexWriter实例,把数据给ramDir, 必须要先关闭,然后才能调用addIndexes方法把ramDir参数传入;
ramWriter.close();
//通过disk的IndexWriter实例的addIndexes
diskWriter.addIndexes(new Directory[]{ramDir});
diskWriter.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static Query queryParser(){
QueryParser queryParser = new QueryParser("value", new StandardAnalyzer());
try {
Query query = queryParser.parse("world");
return query;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void search(){
try {
IndexSearcher search = new IndexSearcher(path);
Query query = queryParser();
Hits hits = search.search(query);
if(hits==null)
return;
for (int i = 0; i < hits.length(); i++) {
Document doc = hits.doc(i);
System.out.println("id = "+hits.id(i));
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}