通过addIndexes将内存中的索引加入到磁盘索引


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();
}
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值