Example usage for org.apache.lucene.index IndexWriter close

List of usage examples for org.apache.lucene.index IndexWriter close

Introduction

In this page you can find the example usage for org.apache.lucene.index IndexWriter close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes all open resources and releases the write lock.

Usage

From source file:com.github.wxiaoqi.search.lucene.LuceneDao.java

License:Open Source License

public void create(IndexObject indexObject) {

    IndexWriter indexWriter = null;
    try {/*from w  w w. jav  a2 s. co m*/
        IndexWriterConfig config = new IndexWriterConfig(this.getAnalyzer());
        indexWriter = new IndexWriter(this.getDirectory(), config);
        indexWriter.addDocument(DocumentUtil.IndexObject2Document(indexObject));
        indexWriter.commit();
    } catch (Exception e) {
        e.printStackTrace();
        try {
            indexWriter.rollback();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    } finally {
        try {
            indexWriter.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.github.wxiaoqi.search.lucene.LuceneDao.java

License:Open Source License

public void deleteAll() {
    IndexWriter indexWriter = null;
    try {// w  ww  .j a  v  a 2s  . c o m
        IndexWriterConfig config = new IndexWriterConfig(this.getAnalyzer());
        indexWriter = new IndexWriter(this.getDirectory(), config);
        Long result = indexWriter.deleteAll();
        /**/
        indexWriter.forceMergeDeletes();
        log.info("deleted:{}", result);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            indexWriter.rollback();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    } finally {
        try {
            indexWriter.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.github.wxiaoqi.search.lucene.LuceneDao.java

License:Open Source License

public void update(IndexObject indexObject) {

    IndexWriter indexWriter = null;

    try {//from   w  w w.  j a  va2  s. c o  m

        Term term = new Term("id", indexObject.getId().toString());
        IndexWriterConfig config = new IndexWriterConfig(this.getAnalyzer());
        indexWriter = new IndexWriter(this.getDirectory(), config);
        indexWriter.updateDocument(term, DocumentUtil.IndexObject2Document(indexObject));

    } catch (Exception e) {
        e.printStackTrace();
        try {
            indexWriter.rollback();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    } finally {
        try {
            indexWriter.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.github.wxiaoqi.search.lucene.LuceneDao.java

License:Open Source License

public void delete(IndexObject indexObject) {
    IndexWriter indexWriter = null;
    try {//from   ww  w  . ja va2s .c  o m
        Term term = new Term("id", indexObject.getId().toString());
        IndexWriterConfig config = new IndexWriterConfig(this.getAnalyzer());
        indexWriter = new IndexWriter(this.getDirectory(), config);
        indexWriter.deleteDocuments(term);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            indexWriter.rollback();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    } finally {
        try {
            indexWriter.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.globalsight.ling.lucene.Index.java

License:Apache License

/** Opens or creates this index. */
public void open() throws IOException {
    synchronized (m_state) {
        if (m_state != STATE_CLOSED) {
            throw new IOException("index is open");
        }//from  w  w  w.  ja v a  2s . c om

        m_state = STATE_OPENING;
    }

    try {
        if (!DirectoryReader.indexExists(m_fsDir)) {
            // create empty index, close it.
            IndexWriter tempWriter = getIndexWriter(true);
            tempWriter.close();
            tempWriter = null;
        }
    } finally {
        m_state = STATE_OPENED;
    }
}

From source file:com.globalsight.ling.lucene.Index.java

License:Apache License

/** Optimizes this index, merging all recent changes into a single file. */
public void optimize() throws IOException {
    synchronized (m_state) {
        if (m_state != STATE_OPENED) {
            throw new IOException("index is not available");
        }//from   w ww.java  2s .  c o  m

        // disable new readers & writers
        m_state = STATE_CREATING;
    }

    try {
        // Other readers will finish and release this object.
        // We wait for this to happen by acquiring the lock.
        m_lock.writeLock().acquire();

        try {
            // allocate writer and optimize index
            IndexWriter tempWriter = getIndexWriter(false);
            // m_ramIndexWriter.optimize();
            tempWriter.close();
            tempWriter = null;
        } finally {
            m_lock.writeLock().release();
            m_state = STATE_OPENED;
        }
    } catch (InterruptedException ex) {
        throw new IOException(ex.getMessage());
    }
}

From source file:com.globalsight.ling.lucene.Index.java

License:Apache License

public void deleteDocument(long p_mainId, long p_subId) throws IOException {
    synchronized (m_state) {
        if (m_state != STATE_OPENED) {
            throw new IOException("index is not available");
        }/*from  ww  w. j a  v  a 2s  .co  m*/
    }

    // clean cache if have
    LuceneCache.cleanLuceneCache(m_directory);

    try {
        m_lock.writeLock().acquire();

        try {
            IndexWriter w = getIndexWriter(true);
            //                IndexReader reader = DirectoryReader.open(m_fsDir);
            //                reader.delete(new Term(
            //                    IndexDocument.SUBID, String.valueOf(p_subId)));
            w.deleteDocuments(new Term(IndexDocument.SUBID, String.valueOf(p_subId)));

            w.close();
        } finally {
            m_lock.writeLock().release();
        }
    } catch (InterruptedException ex) {
        throw new IOException(ex.getMessage());
    }
}

From source file:com.globalsight.ling.tm2.lucene.LuceneIndexWriter.java

License:Apache License

/**
 * Indexes segments. To maintain index integrity, indexes are at
 * first created in memory and merged into a file system index.
 *
 * @param p_tuvs List of BaseTmTuv, SegmentsForSave.AddTuv, or TM3Tuv
 * @param p_sourceLocale true if p_tuvs are source locale segments
 * @param p_indexTargetLocales true for TM3, false for TM2
 *//*from   w w w  .  ja  va  2 s. c  o m*/
public void index(List p_tuvs, boolean p_sourceLocale, boolean p_indexTargetLocales) throws Exception {
    IndexWriterConfig conf = new IndexWriterConfig(LuceneUtil.VERSION, m_analyzer);
    conf.setOpenMode(m_isFirst ? OpenMode.CREATE : OpenMode.CREATE_OR_APPEND);
    IndexWriter fsIndexWriter = new IndexWriter(m_directory, conf);

    try {
        for (Iterator it = p_tuvs.iterator(); it.hasNext();) {
            Object tuv = it.next();

            Document doc = tuv instanceof BaseTmTuv
                    ? createDocumentFromBaseTmTuv((BaseTmTuv) tuv, p_sourceLocale, p_indexTargetLocales)
                    : tuv instanceof AddTuv
                            ? createDocumentFromAddTuv((AddTuv) tuv, p_sourceLocale, p_indexTargetLocales)
                            : tuv instanceof TM3Tuv
                                    ? createDocumentFromTM3Tuv((TM3Tuv<GSTuvData>) tuv, p_sourceLocale,
                                            p_indexTargetLocales)
                                    : null;

            fsIndexWriter.addDocument(doc);
        }
    } finally {
        fsIndexWriter.close();
    }

    // clean cache if have
    LuceneCache.cleanLuceneCache(m_indexDir);
}

From source file:com.globalsight.ling.tm2.lucene.LuceneIndexWriter.java

License:Apache License

public void remove(Collection p_tuvs) throws Exception {
    IndexWriterConfig conf = new IndexWriterConfig(LuceneUtil.VERSION, m_analyzer);
    conf.setOpenMode(OpenMode.CREATE_OR_APPEND);
    IndexWriter writer = new IndexWriter(m_directory, conf);

    try {//www .j  av a2 s .  co m
        for (Iterator it = p_tuvs.iterator(); it.hasNext();) {
            Object tuv = it.next();
            Long id = tuv instanceof BaseTmTuv ? ((BaseTmTuv) tuv).getId()
                    : tuv instanceof TM3Tuv ? ((TM3Tuv) tuv).getId() : null;

            Term term = new Term(TuvDocument.TUV_ID_FIELD, id.toString());
            writer.deleteDocuments(term);
        }
    } catch (Throwable e) {
        c_logger.error(e.getMessage(), e);
        //indexReader.undeleteAll();
        throw (e instanceof Exception ? (Exception) e : new Exception(e));
    } finally {
        writer.commit();
        writer.close();
    }

    // clean cache if have
    LuceneCache.cleanLuceneCache(m_indexDir);
}

From source file:com.gmail.mosoft521.luceneDemo.IndexFiles.java

License:Apache License

/**
 * Index all text files under a directory.
 *//*from  w  w w .  j  a  v  a  2  s.c o m*/
public static void main(String[] args) {
    String usage = "java org.apache.lucene.demo.IndexFiles"
            + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
            + "This indexes the documents in DOCS_PATH, creating a Lucene index"
            + "in INDEX_PATH that can be searched with SearchFiles";
    String indexPath = "index";
    String docsPath = null;
    boolean create = true;
    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            indexPath = args[i + 1];
            i++;
        } else if ("-docs".equals(args[i])) {
            docsPath = args[i + 1];
            i++;
        } else if ("-update".equals(args[i])) {
            create = false;
        }
    }

    if (docsPath == null) {
        System.err.println("Usage: " + usage);
        System.exit(1);
    }

    final File docDir = new File(docsPath);
    if (!docDir.exists() || !docDir.canRead()) {
        System.out.println("Document directory '" + docDir.getAbsolutePath()
                + "' does not exist or is not readable, please check the path");
        System.exit(1);
    }

    Date start = new Date();
    try {
        System.out.println("Indexing to directory '" + indexPath + "'...");

        Directory dir = FSDirectory.open(new File(indexPath));
        // :Post-Release-Update-Version.LUCENE_XY:
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_48);
        IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_48, analyzer);

        if (create) {
            // Create a new index in the directory, removing any
            // previously indexed documents:
            iwc.setOpenMode(OpenMode.CREATE);
        } else {
            // Add new documents to an existing index:
            iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
        }

        // Optional: for better indexing performance, if you
        // are indexing many documents, increase the RAM
        // buffer.  But if you do this, increase the max heap
        // size to the JVM (eg add -Xmx512m or -Xmx1g):
        //
        // iwc.setRAMBufferSizeMB(256.0);

        IndexWriter writer = new IndexWriter(dir, iwc);
        indexDocs(writer, docDir);

        // NOTE: if you want to maximize search performance,
        // you can optionally call forceMerge here.  This can be
        // a terribly costly operation, so generally it's only
        // worth it when your index is relatively static (ie
        // you're done adding documents to it):
        //
        // writer.forceMerge(1);

        writer.close();

        Date end = new Date();
        System.out.println(end.getTime() - start.getTime() + " total milliseconds");

    } catch (IOException e) {
        System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
    }
}