我一直在使用lucene.net在WPF C#中进行索引,突然得到了新的每个新文档而不是之前的文档,因此索引中任何时候的文档数量为1
我不知道怎么会发生这种情况,因为我在C#Console中测试了相同的添加方法,但在表单中它只是发生了一些奇怪的事情
你不能建议如何解决这个问题吗?
这是创建索引的方法的代码
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
try
{
LuceneSearch.LuceneEngine le = new LuceneSearch.LuceneEngine();
var engine = new FileEngine();
if (txtboxName.Text != "" && cmbboxDis.SelectedIndex != -1 && btnFile.Content.ToString() != "Choose a file")
{//adds some stuff to DB and returns an object to index
var IndexMe= engine.AddFile(txtboxName.Text, cmbboxDis.SelectedIndex, txtboxAuth.Text, txtboxTags.Text, txtboxComment.Text);
le.BuildIndex(IndexMe);//index this file
this.Close();
}
else
MessageBox.Show("Not all fields are filled", "Oops!", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
MessageBox.Show("You haven't chosen a file! " +ex.Message, "Ошибка!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
这就是它在lucene方法课程中的表现方式
namespace StudentWorksSearch.LuceneSearch
{
public class LuceneEngine
{//get directory
private const string _luceneDir = "../../../Data/lucene_index1";
private FSDirectory _directoryTemp;
private FSDirectory _directory
{
get
{
if (_directoryTemp == null) _directoryTemp = FSDirectory.Open(new
DirectoryInfo(_luceneDir));
if (IndexWriter.IsLocked(_directoryTemp)) IndexWriter.Unlock(_directoryTemp);
var lockFilePath = Path.Combine(_luceneDir, "write.lock");
if (File.Exists(lockFilePath)) File.Delete(lockFilePath);
return _directoryTemp;
}
}
//this method creates document from an ObjectToIndex
public void BuildIndex(FileToIndex file)
{
using (var analyzer = new Lucene.Net.Analysis.Ru.RussianAnalyzer(Version.LUCENE_30))
{
using (IndexWriter idxw = new IndexWriter(_directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED))
{
//check if document exists, if true deletes existing
var searchQuery = new TermQuery(new Term("Id", file.Id.ToString()));
idxw.DeleteDocuments(searchQuery);
//creation
Document doc = new Document();
doc.Add(new Field("Id", file.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//аналайзер разбивает строки на слова
doc.Add(new Field("Title", file.Title, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("Description", file.Description, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("Authors", file.Authors, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("Text", file.Text, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("Hashtags", file.Hashtags, Field.Store.YES, Field.Index.ANALYZED));
//write the document to the index
idxw.AddDocument(doc);
//optimize and close the writer
idxw.Commit();
idxw.Optimize();
}
}
}
答案 0 :(得分:2)
IndexWriter构造函数的第三个参数指定是否应该创建新索引。如果它设置为true
,它将覆盖任何现有索引并创建一个新索引。您应该将其设置为false
以打开现有索引:
IndexWriter idxw = new IndexWriter(_directory, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED