I am working on a project that relies on Lucene.NET. Up to this point, I have had a class that had simple name/value properties (like int ID { get; set; }). However, I now need to add a new property to my index. The property is a type of List. Up to this point, I've updated my index like so...
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);
}
Now, MyResult has a property that represents a List. How do I put that in my index? The reason I need to add it to my index is so that I can get it back out later.
You can add each value in the list as a new field with the same name (lucene supports that) and later read those values back into a string list:
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);
}
Here's how to extract the values from a search result:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With