2013-04-03 58 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