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

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

Introduction

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

Prototype

public final void flush() throws IOException 

Source Link

Document

Moves all in-memory segments to the Directory , but does not commit (fsync) them (call #commit for that).

Usage

From source file:com.redhat.satellite.search.index.IndexManager.java

License:Open Source License

/**
 * Create an empty index if it exists//  ww  w  . j  ava 2  s.c  om
 *
 * @param indexName index to use
 * @param lang language.
 * @throws IndexingException something went wrong adding the document
 */
public void createIndex(String indexName, String lang) throws IndexingException {

    try {
        IndexWriter writer = getIndexWriter(indexName, lang);
        try {
            writer.flush();
        } finally {
            try {
                writer.close();
            } finally {
                // unlock it if it is locked.
                unlockIndex(indexName);
            }
        }
    } catch (CorruptIndexException e) {
        throw new IndexingException(e);
    } catch (LockObtainFailedException e) {
        throw new IndexingException(e);
    } catch (IOException e) {
        throw new IndexingException(e);
    }
}

From source file:com.redhat.satellite.search.index.IndexManager.java

License:Open Source License

/**
 * Adds a document to an index/*from ww w.  j a v  a2  s  .c  om*/
 *
 * @param indexName index to use
 * @param doc Document to be indexed.
 * @param lang language.
 * @throws IndexingException something went wrong adding the document
 */
public void addToIndex(String indexName, Document doc, String lang) throws IndexingException {

    try {
        IndexWriter writer = getIndexWriter(indexName, lang);
        try {
            writer.addDocument(doc);
            writer.flush();
        } finally {
            try {
                writer.close();
            } finally {
                // unlock it if it is locked.
                unlockIndex(indexName);
            }
        }
    } catch (CorruptIndexException e) {
        throw new IndexingException(e);
    } catch (LockObtainFailedException e) {
        throw new IndexingException(e);
    } catch (IOException e) {
        throw new IndexingException(e);
    }
}

From source file:de.u808.simpleinquest.indexer.impl.IndexUpdater.java

License:Apache License

private void indexDocuments(List<File> files)
        throws CorruptIndexException, LockObtainFailedException, IOException {
    IndexWriter indexWriter = new IndexWriter(indexDirectory, new StandardAnalyzer());
    Iterator<File> iterator = files.iterator();
    while (iterator.hasNext()) {
        File file = (File) iterator.next();
        if (file.isDirectory()) {
            Document doc = DirectoryDocument.Document(file);
            indexWriter.addDocument(doc);
        } else {//from w ww  .j  a v a  2 s.c  om
            Indexer indexer = indexerFactory.getIndexer(file);
            if (indexer != null) {
                Document document = null;
                try {
                    log.debug("Memory before indexing in MB (M: "
                            + memoryFormater.format(Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " T: "
                            + memoryFormater.format(Runtime.getRuntime().totalMemory() / (1024 * 1024)) + "F: "
                            + memoryFormater.format(Runtime.getRuntime().freeMemory() / (1024 * 1024)) + ")");
                    this.ensureEnoughHeapMemory();
                    String msg = "Indexing file: " + file.getPath();
                    document = indexer.indexFile(file);
                    this.setStatusMessage(msg);
                    log.info(msg);
                    log.debug("Memory after indexing in MB (M: "
                            + memoryFormater.format(Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " T: "
                            + memoryFormater.format(Runtime.getRuntime().totalMemory() / (1024 * 1024)) + " F: "
                            + memoryFormater.format(Runtime.getRuntime().freeMemory() / (1024 * 1024)) + ")");
                    iterator.remove();
                } catch (IndexerException e) {
                    log.error("Error during indexing", e);
                } catch (OutOfMemoryError outOfMemoryError) {
                    log.warn(
                            "File seems to be to big for the actual free heap. Try to increase availible memory with vm option -Xmx if this is a recurring error message");
                    log.info("Try to free memory");
                    document = null;
                    System.gc();
                    this.refreschIndex();
                }
                if (document != null) {
                    indexWriter.addDocument(document);
                } else {
                    String msg = "Indexer " + indexer.getClass() + " returned no content to index";
                    this.setStatusMessage(msg);
                    log.warn(msg);
                }
            } else {
                log.debug("No indexer for file: " + file.getPath());
            }
        }
    }
    String msg = "Optimizing index";
    this.setStatusMessage(msg);
    log.info(msg);
    indexWriter.flush();
    indexWriter.optimize();
    msg = "Index optimized";
    this.setStatusMessage(msg);
    log.info(msg);
    indexWriter.close(true);
    indexWriter = null;
}

From source file:es.pode.indexador.negocio.servicios.indexado.SrvIndexadorServiceImpl.java

License:Open Source License

private void cierraIndicesWROptimiza(Hashtable indicesAbiertosWR) throws Exception {
    if (indicesAbiertosWR == null || indicesAbiertosWR.isEmpty())
        //         no hacemos nada
        return;/*w  w  w  .  j av a 2 s.  com*/

    //      Hacemos efectivos los cambios en los indices
    try {
        for (Enumeration e = indicesAbiertosWR.elements(); e.hasMoreElements();) {
            IndexWriter indiceEscritura = (IndexWriter) e.nextElement();
            indiceEscritura.flush();
            indiceEscritura.optimize();
            indiceEscritura.getDirectory().clearLock(indiceEscritura.getDirectory().getLockID());
            indiceEscritura.getDirectory().close();
            indiceEscritura.close();
        }
    } catch (Exception e1) {
        logger.error("Error realizando flush sobre los indices abiertos[" + e1.getCause() + "]");
        throw new Exception("Error realizando flush sobre los indices abiertos.", e1);
    }
    //      Modificamos los  spell checker por idiomas
    //      - Reseteamos los spell
    //      - Regeneramos su informacion
    try {
        for (Enumeration e = indicesAbiertosWR.keys(); e.hasMoreElements();) {
            String locale = (String) e.nextElement();
            Directory directorioIndiceSpell = this.indiceSpell(locale);
            //            Eliminamos la informacion del spell checker para regenerarla de nuevo
            spellCheckerReset(directorioIndiceSpell);
            if (directorioIndiceSpell != null) {
                this.spellCheckerAdd(this.getDirectorioPorLocale(locale), directorioIndiceSpell);
            }
        }
    } catch (Exception e) {
        logger.error("Error actualizando Spell Checkers de los indices[" + e.getCause() + "]");
        throw new Exception("Error actualizando Spell Checkers de los indices.", e);
    }
}

From source file:es.pode.indexador.negocio.servicios.indexado.SrvIndexadorServiceImpl.java

License:Open Source License

/**
 * Reindexado de ODEs/*from w  w w.j a v a2 s .c  o m*/
 * @param localizador Objeto donde le indicamos la localizacin fsica del fichero immsmanifiestxml 
 * y el identificador del ODE a reindexar
 * @throws java.lang.Exception
 * @see es.pode.indexador.negocio.servicios.SrvIndexadorService#reindexarODE(java.lang.String)
 */
protected IndexadorVO[] handleReindexarODE(es.pode.indexador.negocio.servicios.indexado.IdODEVO[] localizador)
        throws java.lang.Exception {
    // El objeto esta indexado.
    // Para reindexar un documento hay que utilizar el index writer y no el index modifier, que esta deprecated

    ArrayList respuestas = new ArrayList();
    if (localizador != null || localizador.length > 0) {
        //         Abrimos todos los indices de escritura para todos los idiomas en prevision de aceptar ODEs de diferentes
        //         idiomas
        Hashtable indicesWR = new Hashtable();
        try {
            indicesWR = abrirIndicesWR();
        } catch (RuntimeException e) {
            logger.error("Error abriendo los indices de los idiomas indexados para reindexacion[" + e.getCause()
                    + "]");
            throw new Exception("Error abriendo los indices de los idiomas indexados para reindexacion", e);
        }
        for (int x = 0; x < localizador.length; x++) {
            //            Vemos si hay un indice donde reindexar el ODE. Utilizamos su idioma.
            if (localizador[x].getCatalogacionPrimaria() != null
                    && indicesWR.get(localizador[x].getCatalogacionPrimaria().getIdioma()) != null) {
                String locale = localizador[x].getCatalogacionPrimaria().getIdioma();

                //               procedemos a actualizar los indices
                //               Obtenemos el indice de escritura para realizar la modificacion
                Analyzer analizador = this.obtenerAnalyzer(locale);
                IndexWriter indiceAModificar = (IndexWriter) indicesWR.get(locale);
                //               Borramos documento a re-indexar
                if (logger.isDebugEnabled())
                    logger.debug("Obtenemos indice de escritura para reindexar Documento con indentificador["
                            + localizador[x].getIdODE() + "] en indice[" + locale + "]");
                //               Calculamos el termino por el que vamos a sustituir los documentos del indice
                Term terminoABorrar = new Term(props.getProperty("campo_identificadorODE"),
                        localizador[x].getIdODE());
                //               Con los campos del ODE que nos pasan para indexar generamos un documento nuevo
                Document doc = this.generarDoc(localizador[x]);
                //               Actualizamos el documento dentro del indice
                indiceAModificar.updateDocument(terminoABorrar, doc, analizador);
                indiceAModificar.flush();
                //               Preparamos la respuesta de exito fracaso para la vuelta
                respuestas.add(rellenarVO(localizador[x].getLocalizadorODE(), 0, "Reindexacin correcta"));
            } else {
                String idiomaFalso = (localizador[x].getCatalogacionPrimaria() != null)
                        ? localizador[x].getCatalogacionPrimaria().getIdioma()
                        : "null";
                if (logger.isDebugEnabled())
                    logger.debug("Error reindexando ODE con identificador[" + localizador[x].getIdODE()
                            + "] e idioma[" + idiomaFalso
                            + "]. No hay indice para este idioma de catalogacion.");
                respuestas.add(rellenarVO(localizador[x].getLocalizadorODE(), 1, "Reindexacin incorrecta"));
            }
        }
        //         Cerramos los indices de escritura y regeneramos los spell checkers
        try {
            cierraIndicesWROptimiza(indicesWR);
        } catch (RuntimeException e) {
            logger.error(
                    "Error cerrando los indices de escritura despues de eindexacion[" + e.getCause() + "]");
            throw new Exception("Error cerrando los indices de escritura despues de eindexacion", e);
        }
    } else {
        logger.error("No hay ODEs para reindexar");
        throw new Exception("No hay ODEs para reindexar");
    }

    return (IndexadorVO[]) respuestas.toArray(new IndexadorVO[respuestas.size()]);
}

From source file:es.pode.indexador.negocio.servicios.indexado.SrvIndexadorServiceImpl.java

License:Open Source License

/**
 * Eliminacion de ODEs de los indices.//from w  w w  . j  a  va  2s  .c om
 * @param idODE Array de identificadores alfanumericos de los ODEs que se quieren eliminar. 
 * @throws java.lang.Exception
 * @see es.pode.indexador.negocio.servicios.SrvIndexadorService#eliminarODE(java.lang.String)
 */
protected IndexadorVO[] handleEliminarODE(String[] idODE) throws java.lang.Exception {
    ArrayList respuestas = new ArrayList();
    if (idODE != null || idODE.length > 0) {
        //         Abrimos todos los indices de lectura para eliminar todos los ODEs de todos los indices que hay
        Hashtable indicesWR = new Hashtable();
        try {
            indicesWR = abrirIndicesWR(); //lo intentamos con los indices de escritura
        } catch (RuntimeException e) {
            logger.error("Error abriendo los indices de los idiomas indexados para eliminacion[" + e.getCause()
                    + "]");
            throw new Exception("Error abriendo los indices de los idiomas indexados para eliminacion", e);
        }
        //         Si no hay indices sobre los que actuar, devuelvo exito.
        if (indicesWR == null || indicesWR.size() <= 0) {
            logger.warn("Error eliminando ODEs. No hay indices sobre los que eliminar.");
            for (int x = 0; x < idODE.length; x++)
                respuestas.add(new IndexadorVO(idODE[x], 0, "Borrado correcto."));
            return (IndexadorVO[]) respuestas.toArray(new IndexadorVO[respuestas.size()]);
        }
        //         Me recorro las claves de la tabla(idiomas) para ir borrando para cada una los odes
        for (Enumeration e = indicesWR.keys(); e.hasMoreElements();) {
            String terminoClave = props.getProperty("campo_identificadorODE");
            String locale = (String) e.nextElement();
            IndexWriter indiceActual = (IndexWriter) indicesWR.get(locale);
            for (int x = 0; x < idODE.length; x++) {
                Term terminoABorrar = new Term(terminoClave, idODE[x]);
                try {
                    try {
                        indiceActual.deleteDocuments(terminoABorrar);
                        respuestas.add(rellenarVO(idODE[x], 0, "Borrado correcto"));
                        logger.info("Documento con idODE[" + idODE[x] + "] borrado del indice[" + locale + "]");
                    } catch (RuntimeException e1) {
                        logger.warn("Intentando borrar documento con idODE[" + idODE[x] + "] del indice["
                                + locale + "] imposible borrar[" + e1.getCause()
                                + "]. Continuamos con el resto del proceso.");
                        respuestas.add(rellenarVO(idODE[x], 1, "Borrado incorrecto"));
                        logger.warn("Aadimos de nuevo a la BD tesauros y areas curriculares del ODE "
                                + idODE[x] + " que habiamos eliminado");
                        logger.warn("Documento con idODE[" + idODE[x] + "] no encontrado en el indice[" + locale
                                + "]");
                    }
                } catch (Exception e1) {
                    logger.warn("Intentando borrar documento con idODE[" + idODE[x] + "] del tesauro [" + locale
                            + "] imposible borrar[" + e1.getCause()
                            + "]. Continuamos con el resto del proceso.");
                    respuestas.add(rellenarVO(idODE[x], 1, "Borrado del tesauro incorrecto"));
                    logger.warn("Documento con idODE[" + idODE[x] + "] no encontrado en el tesauro[" + locale
                            + "]");

                }
                indiceActual.flush();
            }
        }
        //         Cerramos los indices de escritura y regeneramos los spell checkers
        try {
            cierraIndicesWROptimiza(indicesWR);
        } catch (RuntimeException e) {
            logger.error("Error cerrando los indices de lectura despues de borrado[" + e.getCause() + "]");
            throw new Exception("Error cerrando los indices de lectura despues de borrado", e);
        }
    } else {
        logger.error("No hay ODEs para borrar");
        throw new Exception("No hay ODEs para borrar");
    }
    return (IndexadorVO[]) respuestas.toArray(new IndexadorVO[respuestas.size()]);
}

From source file:es.pode.indexador.negocio.servicios.indexado.SrvIndexadorServiceImpl.java

License:Open Source License

/**
 * Eliminacin de todos los documentos de un repositorio de ndices
 * Ademas regenera las sugerencias eliminando los elementos que sobran y regenerandose con los que quedan.
 * //from w  ww .ja v  a2s .c o  m
 * @param locale. Nos indica el repositorio del que se quieren eliminar todos los documentos.
 * @return Nmero de documentos eliminados
 * @throws java.lang.Exception
 */
private int borradoTodosDocumentos(String locale,
        es.pode.indexador.negocio.servicios.indexado.IdODEVO[] localizadores) throws java.lang.Exception {
    IndexWriter indiceAModificar = null;
    int numDocumentos = 0;
    try {
        indiceAModificar = this.indiceEscritura(locale);
        if (localizadores != null)
            numDocumentos = localizadores.length;

        logger.debug("Numero de documentos: " + numDocumentos);

        for (int i = 0; i < numDocumentos; i++) {
            Term terminoABorrar = new Term(props.getProperty("campo_identificadorODE"),
                    localizadores[i].getIdODE());

            logger.debug("terminoABorrar - localizadorODE[" + localizadores[i].getIdODE() + "]");
            logger.debug("terminoABorrar[" + terminoABorrar + "]");
            indiceAModificar.deleteDocuments(terminoABorrar);
        }
        logger.debug("Se han eliminado " + numDocumentos + " documentos del ndice");
        indiceAModificar.flush();
    } catch (Exception e) {
        logger.error("Error borrando documentos " + e);
        throw new Exception(e);
    } finally {
        if (indiceAModificar != null)
            indiceAModificar.close();
        Directory directorioIndiceSpell = this.indiceSpell(locale);
        //         Eliminamos la informacion del spell checker para regenerarla de nuevo
        spellCheckerReset(directorioIndiceSpell);
        spellCheckerAdd(this.getDirectorioPorLocale(locale), directorioIndiceSpell);
    }

    return numDocumentos;
}

From source file:memedb.fulltext.Lucene.java

License:Apache License

public void onFulltextResult(memedb.document.Document doc, org.apache.lucene.document.Document luceneDoc)
        throws FulltextException {
    if (luceneDoc == null)
        return;/*from   w ww  .  ja v  a 2 s.  com*/
    //      log.debug("onFulltextResult : {} luceneDoc {}", doc.getDatabase(), luceneDoc.toString());
    log.debug("onFulltextResult : {}", doc.getDatabase());
    String db = doc.getDatabase();
    IndexWriter writer = writers.get(db);
    if (writer == null) {
        log.error("Missing IndexWriter for database {}", db);
        return;
    }
    try {
        writer.addDocument(luceneDoc);
        writer.flush();
    } catch (CorruptIndexException e) {
        throw new IndexCorruptException(db);
    } catch (IOException e) {
        throw new FulltextException(db);
    }
}

From source file:org.eclipse.ecr.core.storage.sql.db.H2Fulltext.java

License:Open Source License

private static void removeIndexFiles(Connection conn) throws SQLException {
    String path = getIndexPath(conn);
    IndexWriter index = indexWriters.remove(path);
    if (index != null) {
        try {//from   w  w w  . java  2s.c om
            index.flush();
            index.close();
        } catch (IOException e) {
            throw convertException(e);
        }
    }
    FileSystem.getInstance(path).deleteRecursive(path);
}

From source file:org.eclipse.smila.search.lucene.index.access.IndexWriterPool.java

License:Open Source License

/**
 * Flushes the IndexWriter for the given indexName. Quietly ignores any not existing index names.
 * //from  ww w. j av  a 2  s.c om
 * @param indexName
 *          the name of the index
 * @throws IndexException
 *           if any error occurs
 */
public static void flushIndexWriter(final String indexName) throws IndexException {
    final IndexWriter indexWriter = POOL.get(indexName);
    if (indexWriter != null) {
        try {
            indexWriter.flush();
            if (LOG.isInfoEnabled()) {
                LOG.info("Flushed Lucene index " + indexName);
            }
        } catch (final Exception e) {
            throw new IndexException(e);
        }
    }
}