Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing List of Strings in Lucene.NET

Tags:

c#

lucene.net

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.

like image 237
Eels Fan Avatar asked Apr 03 '13 16:04

Eels Fan


1 Answers

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);
    }
}
like image 100
Omri Avatar answered Oct 11 '22 13:10

Omri