You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@lucenenet.apache.org by Trevor Watson <tw...@datassimilate.com> on 2012/07/23 17:05:21 UTC
C# - Bulk Update
I've come across this piece of code in a project that I've been
working on and was wondering if there's a more efficient way to
bulk-update items. I know there is no in-library bulk update and we'll
have to loop through documents, but this seemed messy to me.
Any assistance would be greatly appreciated
Trevor
----------- C# Code Start -----------
public static int BulkUpdateField(string indexPath, string
queryString, string fieldName, object newValue)
{
int rowCount = 0;
// Create needed Lucene connections
using (IndexReader reader = IndexReader.Open(new
Lucene.Net.Store.SimpleFSDirectory(new DirectoryInfo(indexPath))))
using (Lucene.Net.Analysis.Analyzer analyzer = getAnalyzer())
using (Lucene.Net.Search.Searcher searcher =
getSearcher(indexPath))
using (IndexWriter writer = new IndexWriter(new
Lucene.Net.Store.SimpleFSDirectory(new DirectoryInfo(indexPath)), false,
analyzer, false))
{
// Create query
Lucene.Net.QueryParsers.QueryParser qp = new
Lucene.Net.QueryParsers.QueryParser("FileId", analyzer);
Query query = qp.Parse(queryString);
// Run query (to get total count of documents)
TopDocs td = searcher.Search(query, 1);
// Make sure there are documents
if (td.TotalHits == 0)
return 0;
// Get all documents in query
td = searcher.Search(query, td.TotalHits);
// Foreach document
foreach (ScoreDoc doc in td.ScoreDocs)
{
rowCount++;
// Update document
Document currentDoc = reader.Document(doc.Doc);
currentDoc.GetField(fieldName).SetValue(newValue.ToString());
// Resave document
writer.UpdateDocument(new Term("FileId",
currentDoc.GetField("FileId").StringValue()), currentDoc);
}
// Clean out deletes from UpdateDocument
writer.ExpungeDeletes();
// Save to index
writer.Commit();
// Close connections
writer.Close();
reader.Close();
searcher.Close();
analyzer.Close();
}
return rowCount;
}
----------- C# Code End -----------