现在的位置: 首页 > 综合 > 正文

通过dotLucene实现增量索引.

2011年11月25日 ⁄ 综合 ⁄ 共 1878字 ⁄ 字号 评论关闭

不知道以前, 觉得很难. 实现以后觉得太容易了.

主要是初始化IndexWriter的时候, 不初始化新的, 而是先读Search目录. 附上源代码.
注释了的是我以前的老代码, 那时候不能进行增量.

using System;

using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Analysis.Cn;
using Lucene.Net.Analysis.CJK;

namespace SearchEnginer {
    
public sealed class Indexer : IDisposable {
    
//    Directory dir = null;
        IndexWriter writer = null;

        
private Indexer() {
        }


        
public Indexer (string physicalPath, bool create, bool useTempDirectory) {
        
//    if(useTempDirectory) {
        
//        physicalPath = System.IO.Path.Combine(physicalPath, "tempindex");
        
//    }

            ChineseAnalyzer analyzer 
= new ChineseAnalyzer();
        
//    dir = FSDirectory.GetDirectory(physicalPath, create);

            writer 
= GetWriter(physicalPath);//new IndexWriter(dir, analyzer, create);
            writer.mergeFactor = 15;
        }


        
public void AddDocument (Document doc) {
            writer.AddDocument(doc);
        }


        
private IndexWriter GetWriter(string physicalPath) {
            IndexWriter indexWriter 
= null;
            
            
string segmentFile = System.IO.Path.Combine(physicalPath, "segments");

            
if ( System.IO.File.Exists(segmentFile) )
                indexWriter 
= new IndexWriter(physicalPath, new Lucene.Net.Analysis.Cn.ChineseAnalyzer(), false);
            
else
                indexWriter 
= new IndexWriter(physicalPath, new Lucene.Net.Analysis.Cn.ChineseAnalyzer(), true);

            
return indexWriter;
        }


        
public void Close() {
            
if (!disposed) {
            
//    dir.Close();
                writer.Optimize();
                writer.Close();
                disposed 
= true;
            }

        }


        
private bool disposed = false;

        
public void Dispose() {
            Close();
        }

    }

}

参考: http://info.hustonline.net/info/document/doc.aspx?ID=639

抱歉!评论已关闭.