2013-04-03 62 views
6

我正在研究一個依賴Lucene.NET的項目。到目前爲止,我有一個具有簡單名稱/值屬性的類(如int ID {get; set;})。但是,我現在需要爲我的索引添加一個新屬性。該屬性是一種List。到現在爲止,我已經更新了我的指標是這樣的...在Lucene.NET中存儲字符串列表

MyResult result = GetResult(); 
using (IndexWriter indexWriter = Initialize()) 
{ 
    var document = new Document(); 
    document.Add(new Field("ID", result.ID.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZE)); 
    indexWriter.AddDocument(document); 
} 

現在,MyResult有表示列表的屬性。我如何把它放在我的索引中?我需要將它添加到我的索引中的原因是爲了以後可以將其恢復。

+0

您是否考慮過使用存儲無模式,非結構化文檔而不是鍵 - 值對的東西?這將解決你的問題(一些例子,RavenDB,elasticsearch,MongoDB)。否則,您必須爲包含數組信息以及嵌套屬性信息的鍵生成一個符號(很簡單,但是PITA,如上所述,有些事情已經這樣做了)。 – casperOne

+0

你的清單包含什麼?它需要被搜索嗎? –

+0

該列表不需要被搜索。 –

回答

7

您可以在列表中的一個新領域具有相同名稱添加的每個值(Lucene的支持),後來讀這些值回字符串列表:

MyResult result = GetResult(); 
using (IndexWriter indexWriter = Initialize()) 
{ 
    var document = new Document(); 
    document.Add(new Field("ID", result.ID.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZE)); 

    foreach (string item in result.MyList) 
    { 
     document.Add(new Field("mylist", item, Field.Store.YES, Field.Index.NO)); 
    } 

    indexWriter.AddDocument(document); 
} 

以下是如何從提取值一個搜索結果:

MyResult result = GetResult(); 
result.MyList = new List<string>(); 

foreach (IFieldable field in doc.GetFields()) 
{ 
    if (field.Name == "ID") 
    { 
     result.ID = int.Parse(field.StringValue); 
    } 
    else if (field.Name == "myList") 
    { 
     result.MyList.Add(field.StringValue); 
    } 
} 
+2

+1,最好的辦法。但是該字段應該使用Field.Index.NO創建,因爲asker指定它不需要被搜索。 –

+0

謝謝,我已經更新了我的答案。 – Omri