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.document.Field.Index; import org.apache.lucene.document.Field.Store; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.store.RAMDirectory; /** * @author Vincnet * @version 2.3 * */ public class Test { public static void main(String[] args) throws CorruptIndexException, LockObtainFailedException, IOException { long data1 = System.currentTimeMillis(); /** * 分别创建两个对象 * */ FSDirectory fsDir = FSDirectory.getDirectory("E://Lucene//Index2//"); RAMDirectory ramDir = new RAMDirectory(); IndexWriter ramwriter = new IndexWriter(ramDir, new StandardAnalyzer(),true); IndexWriter fsdwriter = new IndexWriter(fsDir, new StandardAnalyzer(),true); Document document = new Document(); /** * Field(String name, String value, Field.Store store, Field.Index index) * Create a field by specifying its name, value and how it will be saved in the index. * */ document.add(new Field("name","Vincnet",Store.YES,Index.TOKENIZED)); document.add(new Field("age","18",Store.YES,Index.UN_TOKENIZED)); document.add(new Field("note","this is a test data",Store.YES,Index.TOKENIZED)); ramwriter.addDocument(document); fsdwriter.addDocument(document); ramwriter.flush(); //将fsd里面的索引和ram的索引合并成同一个所以 关键一句 fsdwriter.addIndexes(new Directory[]{ramDir}); ramwriter.close(); fsdwriter.flush(); fsdwriter.close(); IndexSearcher searcher = new IndexSearcher(ramDir); Hits hits = searcher.search(new TermQuery(new Term("name","vincnet"))); for(int i = 0 ; i < hits.length() ; i++){ System.out.println(hits.length()+" "+hits.doc(i).get("name")); } searcher.close(); System.out.println("运行时间 : "+(System.currentTimeMillis() - data1)+" ms"); } }