Lucene.net在创建新索引时覆盖

时间:2014-09-01 16:06:47

标签: c# .net database indexing lucene

我正在尝试创建一个可以添加索引的表单,目前该表单有4个标签,文本框和1个按钮。当我按下按钮我希望创建一个索引时,它会被创建,但每当我创建一个新索引时,旧索引都会被覆盖。我该如何解决这个错误。 另外还有一种方法可以自动为文档生成名称 例如,对于每个文件,我可以将其命名为toy1,toy2等,而不仅仅是var玩具......

namespace luceneForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {


            var toy = new Document();
            toy.Add(new Field("Id", textBox1.Text, Field.Store.YES, Field.Index.ANALYZED));//adding a new field  //Field.Store.Yes = store the field in lucene index  
            toy.Add(new Field("Name", textBox2.Text, Field.Store.YES, Field.Index.ANALYZED));
            toy.Add(new Field("Color", textBox3.Text, Field.Store.YES, Field.Index.ANALYZED));
            toy.Add(new Field("Description", textBox4.Text, Field.Store.YES, Field.Index.ANALYZED));

            Directory directory = FSDirectory.Open(new DirectoryInfo(Environment.CurrentDirectory + "\\luceneFormDemo1")); 

            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
        //to analyze text in lucene index using the lucene 29 version

            var writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
        //Now we need a writer to write documents to the index

            writer.AddDocument(toy);
            writer.Optimize();//to make it faster to search
            writer.Dispose();

        //----------if you run till here the folder will be created

        //----------now to search through our index(we will need a reader)
            MessageBox.Show("Index Saved");
            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
            textBox4.Clear();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

IndexWriter constructor的第三个参数指定是否应创建新索引。将其设置为false以打开旧索引,而不是覆盖它。

var writer = new IndexWriter(directory, analyzer, false, IndexWriter.MaxFieldLength.LIMITED);