Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all index data/files in disk using Apache Lucene?

How can I flush/delete/erase all the index files/data in the disk using Apache Lucene.This is my code so far and still I can't remove index files.Please help me out...

Test:

public class Test {
    private static final String INDEX_DIR = "/home/amila/Lucene/REST/indexing"; 
    public static void main(String[] args) {

         try {
            ContentIndexer contentIndexer = new ContentIndexer(INDEX_DIR);
            contentIndexer.flushDisk();
            System.out.println("Flushed");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ContentIndexer:

public class ContentIndexer {
    private IndexWriter writer;

    public ContentIndexer(String indexDir) throws IOException {

        // create the index
        if (writer == null) {
            writer = new IndexWriter(FSDirectory.open(new File(indexDir)),
                    new IndexWriterConfig(Version.LUCENE_36,
                            new StandardAnalyzer(Version.LUCENE_36)));
        }
    }

    public void flushDisk() {
        try {
            writer.deleteAll();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Edited -- Updated Answer

public class Test {
    private static final String INDEX_DIR = "/home/amila/Lucene/REST/indexing";

    public static void main(String[] args) {

        try {
            IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36,
                    new StandardAnalyzer(Version.LUCENE_36));
            conf.setOpenMode(OpenMode.CREATE);
            Directory directory = FSDirectory.open(new File(INDEX_DIR));

            IndexWriter indexWriter  = new IndexWriter(directory, conf);
            indexWriter.deleteAll();
            indexWriter.commit();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
like image 745
Amila Iddamalgoda Avatar asked Jul 14 '14 09:07

Amila Iddamalgoda


2 Answers

The simplest way is to open IndexWriter with a CREATE mode (via indexWriterConfig.setOpenMode(...)). This removes all existing index files in the given directory.

For older versions IndexWriter constructor also has a special boolean create flag which does the same thing.

like image 129
mindas Avatar answered Sep 22 '22 15:09

mindas


You can use two options :

  1. You can call the delete all method of the writer

    indexWriter.DeleteAll();

  2. You can create a new indexWriter with the create flag set to true ( open mode= created)

    new IndexWriter(_luceneDirectory, _analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);

like image 42
Tal Avissar Avatar answered Sep 19 '22 15:09

Tal Avissar