2009-01-06 54 views
0

我想知道如何使用Lucene.NET進行索引和搜索我的業務實體。我看到NHibernate.Search有這個問題很好的功能,但它仍然需要數據庫。我不需要數據庫,我只想將所有數據存儲在我的Lucene.NET索引中。我也看到像Compass這樣的java框架可以很容易地完成這些工作,但它不是.NET庫。如何使用Lucene.Net索引和搜索業務實體?

對象設計或框架有什麼方法可以解決這個問題嗎?

回答

1

試試這個代碼用Lucene.NET索引一個快照的實體企業 .., 這對類型屬性的明顯的侷限性,需要錯誤檢查,但給你如何實現這一總體思路..

public class IndexHelper 
{ 
    static Analyzer analyzer = new StandardAnalyzer(); 
    // Store the index in memory: 
    static Directory directory = new RAMDirectory(); 
    static IndexWriter iwriter; 

    static Dictionary<string, List<WeakReference>> indexedObjects = new Dictionary<string, List<WeakReference>>(); 

    static IndexHelper() 
    { 
     iwriter = new IndexWriter(directory, analyzer, true); 
     iwriter.SetMaxFieldLength(25000); 
    } 

    public static void IndexObject(object entity) 
    { 
     Document doc = new Document(); 
     PropertyInfo[] entityProperties = entity.GetType().GetProperties(); 
     string entityKey = entity.GetHashCode().ToString(); 

     List<WeakReference> entityList; 

     if (indexedObjects.TryGetValue(entityKey, out entityList) == false) 
     { 
      entityList = new List<WeakReference>(); 
      indexedObjects.Add(entityKey, entityList); 
     } 

     entityList.Add(new WeakReference(entity)); 

     doc.Add(new Field("@HASH", entityKey, Field.Store.YES, Field.Index.UN_TOKENIZED)); 

     foreach (PropertyInfo pInfo in entityProperties) 
     { 
      String propertyName = pInfo.Name; 
      object propertyValue = pInfo.GetValue(entity, null); //Assuming all properties are of non index type 
      String text = "null"; 
      if (propertyValue != null) text = propertyValue.ToString(); 

      doc.Add(new Field(propertyName, text, Field.Store.YES, 
       Field.Index.TOKENIZED)); 
     } 

     iwriter.AddDocument(doc); 
     iwriter.Close(); 

    } 

    public static List<WeakReference> Search(string queryString, string fieldName) 
    { 
     // Now search the index: 
     IndexSearcher isearcher = new IndexSearcher(directory); 

     Lucene.Net.QueryParsers.QueryParser qp = new Lucene.Net.QueryParsers.QueryParser(fieldName, analyzer); 
     qp.SetDefaultOperator(Lucene.Net.QueryParsers.QueryParser.OR_OPERATOR); 
     qp.SetLowercaseExpandedTerms(true); 


     Query query = qp.Parse(queryString); 

     List<WeakReference> results = new List<WeakReference>(); 
     Hits hits = isearcher.Search(query); 
     // Iterate through the results: 
     for (int i = 0; i < hits.Length(); i++) 
     { 
      Document hitDoc = hits.Doc(i); 

      List<WeakReference> matchedObjects; 

      if (indexedObjects.TryGetValue(hitDoc.GetField("@HASH").StringValue(), out matchedObjects)) 
      { 
       results.AddRange(matchedObjects); 
      } 

     } 

     isearcher.Close(); 

     return results; 
    } 
} 

更新:還應考慮這個項目http://www.codeplex.com/linqtolucene