NimazSheik
NimazSheik

Reputation: 51

Lucene.net overwriting when new index is created

I am trying to create a form where i can add an index, currently the form has 4 labels, textboxes and 1 button. When i press the button i want an index to be created, it gets created but whenever i create a new index the old one gets overwritten. How do i tackle this error. Additionally is there a way where i can generate names for the documents automatically eg instead of just var toy, for each document i can name as toy1, toy2 etc...

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();
        }
    }
}

Upvotes: 0

Views: 641

Answers (1)

femtoRgon
femtoRgon

Reputation: 33341

The third argument to the IndexWriter constructor specifies whether a new index should be created. Set it to false in order to open the old index, rather than overwriting it.

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

Upvotes: 2

Related Questions