索引的合并与优化(lucene)

下面就介绍一下索引的建立、合并及优化操作

1.索引格式
其实索引目录有两种格式,一种是除配置文件外,每一个Document独立成为一个文件(这种搜索起来会影响速度)。另一种是全部的Document成一个文件,这样属于复合模式就快了。
2.索引文件可放的位置:
索引可以存放在两个地方1.硬盘,2.内存
放在硬盘上可以用FSDirectory(),放在内存的用RAMDirectory()不过一关机就没了
FSDirectory.getDirectory(File file, boolean create)
FSDirectory.getDirectory(String path, boolean create)两个工厂方法返回目录
New RAMDirectory()就直接可以
再和IndexWriter(Directory d, Analyzer a, boolean create)一配合就行了
如:
IndexWrtier indexWriter = new IndexWriter(FSDirectory.getDirectory(“c://index”,true),new StandardAnlyazer(),true);
IndexWrtier indexWriter = new IndexWriter(new RAMDirectory(),new StandardAnlyazer(),true);
3.索引的合并
这个可用IndexWriter.addIndexes(Directory[] dirs)将目录加进去
来看个例子:

public   void  UniteIndex()  throws  IOException
    {
        IndexWriter writerDisk 
=   new  IndexWriter(FSDirectory.getDirectory( " c:/indexDisk " true ), new  StandardAnalyzer(), true );
        Document docDisk 
=   new  Document();
        docDisk.add(
new  Field( " name " , " 程序员之家 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writerDisk.addDocument(docDisk);
        RAMDirectory ramDir 
=   new  RAMDirectory();
        IndexWriter writerRam 
=   new  IndexWriter(ramDir, new  StandardAnalyzer(), true );
        Document docRam 
=   new  Document();
        docRam.add(
new  Field( " name " , " 程序员杂志 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writerRam.addDocument(docRam);
        writerRam.close();
// 这个方法非常重要,是必须调用的
        writerDisk.addIndexes( new  Directory[]{ramDir});
        writerDisk.close();
    }
    
public   void  UniteSearch()  throws  ParseException, IOException
    {
        QueryParser queryParser 
=   new  QueryParser( " name " , new  StandardAnalyzer());
        Query query 
=  queryParser.parse( " 程序员 " );
        IndexSearcher indexSearcher 
= new  IndexSearcher( " c:/indexDisk " );
        Hits hits 
=  indexSearcher.search(query);
        System.out.println(
" 找到了 " + hits.length() + " 结果 " );
        
for ( int  i = 0 ;i
        {
            Document doc 
=  hits.doc(i);
            System.out.println(doc.get(
" name " ));
        }
}

这个例子是将内存中的索引合并到硬盘上来.
注意:合并的时候一定要将被合并的那一方的IndexWriter的close()方法调用。
4.对索引的其它操作:
IndexReader类是用来操作索引的,它有对Document,Field的删除等操作。 删除及搜索下篇继续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值