I have the following code I wrote:
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
Document doc = new Document();
foreach (string fieldName in Request.Form)
{
if (fieldName == "channelID" && string.IsNullOrEmpty(Request["channelID"]))
{
List<long> channelIDS = new List<long>();
IndexReader indexReader = IndexReader.Open(directory, true);
TermEnum te = indexReader.Terms(new Term("ID"));
do
{
Term t = te.Term();
if (t == null || t.Field() != "channelID") break;
channelIDS.Add(long.Parse(t.Text()));
} while (te.Next());
te.Close();
long nextAvailable = channelIDS.Concat(new[] { long.MaxValue })
.OrderBy(x => x)
.Select((value, index) => new { value, index })
.Where(pair => pair.value != pair.index)
.Select(pair => pair.index)
.First();
doc.Add(new Field(fieldName, nextAvailable.ToString(), Field.Store.YES, Field.Index.ANALYZED));
}
else
{
doc.Add(new Field(fieldName, Request.Form[fieldName], Field.Store.YES, Field.Index.ANALYZED));
}
}
writer.AddDocument(doc);
writer.Optimize();
writer.Close();
The document already in the index has a channelID with a value of 0, and all other fields empty.
I have verified that the data fed to the document has a different channelID (even due all the other fields are empty, same as the existing document.
For some reason, the code updates the single document I already have in Lucene,
instead of adding a new one… what am I missing here?
In your code, you are re-creating the index with every run/method-call. So your previous index is deleted.
IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
BTW, terms are stored sorted in lucene index. You can do your calculations while enumerating the terms.