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

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

Introduction

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

Prototype

public long deleteDocuments(Query... queries) throws IOException 

Source Link

Document

Deletes the document(s) matching any of the provided queries.

Usage

From source file:com.aurel.track.lucene.index.LuceneIndexer.java

License:Open Source License

/**
 * Removes a list of TWorkItems from the workitem index
 * Used by deleting a project (for deleting all of its workitems)
 * @param workItemBeans//from  w  w w .j a v  a2s. c  om
 * @return
 */
public static synchronized void deleteFromWorkItemIndex(List<TWorkItemBean> workItemBeans, Integer fieldID,
        boolean deleteProject) {
    String workItemID;
    if (!LuceneUtil.isUseLucene()) {
        return;
    }
    if (workItemBeans == null) {
        return;
    }
    if (!ClusterBL.indexInstantly()) {
        LOGGER.debug("Index instantly is false by deleting workItemBeans " + workItemBeans.size() + " by field "
                + fieldID + " and deleteProject " + deleteProject);
        return;
    }
    if (LOGGER.isDebugEnabled()) {
        if (deleteProject) {
            LOGGER.debug("Delete " + workItemBeans.size()
                    + " workItems from workItemIndex after deleting a project with all items " + fieldID);
        } else {
            LOGGER.debug("Delete " + workItemBeans.size()
                    + " workItems from workItemIndex after changing a dependency for field " + fieldID
                    + " to add them again");
        }
    }
    IndexWriter indexWriter = getWorkItemIndexWriter();
    if (indexWriter == null) {
        LOGGER.error("IndexWriter null by deleting a list of workItems");
        return;
    }
    try {
        for (TWorkItemBean workItemBean : workItemBeans) {
            workItemID = workItemBean.getObjectID().toString();
            Term term = new Term(LuceneUtil.getFieldName(SystemFields.ISSUENO), workItemID);
            try {
                indexWriter.deleteDocuments(term);
            } catch (Exception e) {
                LOGGER.error("Removing a workItemBean " + workItemID + " from the index failed with "
                        + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    } catch (Exception e) {
    }
    try {
        indexWriter.commit();
    } catch (IOException e) {
        LOGGER.error("Flushing the deleting of workItemBeans failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.bdaum.zoom.lal.internal.lire.IndexingJob.java

License:Open Source License

private boolean doUpdateDocument(IProgressMonitor monitor, boolean create, IndexWriter iw,
        DocumentBuilder builder, Asset asset, List<String> done) {
    String assetId = asset.getStringId();
    if (!create)// w  w w  .j ava2 s  .com
        try {
            iw.deleteDocuments(new Term(DocumentBuilder.FIELD_NAME_IDENTIFIER, assetId));
        } catch (CorruptIndexException e) {
            // ignore for now
        } catch (IOException e) {
            addErrorStatus(Messages.IndexingJob_ioerror_updating_lucene_index, e);
            // Abort
            return true;
        }
    monitor.worked(1);
    try (ByteArrayInputStream in = new ByteArrayInputStream(asset.getJpegThumbnail())) {
        BufferedImage bi = null;
        for (int i = 0; i < 15; i++) {
            bi = ImageIO.read(in);
            if (bi != null)
                break;
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                break;
            }
        }
        monitor.worked(1);
        if (bi == null) {
            addWarningStatus(NLS.bind(Messages.IndexingJob_thumbnail_corrupt, asset.getName()));
            return monitor.isCanceled();
        }
        Document doc;
        try {
            doc = builder.createDocument(bi, assetId);
        } catch (ProviderException e) {
            addErrorStatus(NLS.bind(Messages.IndexingJob_indexing_stopped, e.getMessage()), e);
            return true;
        }
        monitor.worked(7);
        try {
            iw.addDocument(doc);
            done.add(assetId);
        } catch (CorruptIndexException e) {
            addErrorStatus(NLS.bind(Messages.IndexingJob_lucene_index_is_corrupt, dbManager.getIndexPath()), e);
            return true;
        } catch (IOException e) {
            addErrorStatus(Messages.IndexingJob_ioerror_updating_lucene_index, e);
            return true;
        }
        try {
            Thread.sleep(30);
        } catch (InterruptedException e) {
            // do nothing
        }
    } catch (IOException e) {
        addErrorStatus(NLS.bind(Messages.IndexingJob_io_error_when_generating_index_data, asset.getName()), e);
    } catch (Exception e) {
        addErrorStatus(NLS.bind(Messages.IndexingJob_internal_error, asset.getName()), e);
        return true;
    }
    monitor.worked(1);
    return monitor.isCanceled();
}

From source file:com.bdaum.zoom.lal.internal.LireActivator.java

License:Open Source License

public void deleteDocuments(IndexWriter indexWriter, String assetId) throws IOException {
    indexWriter.deleteDocuments(new Term(DocumentBuilder.FIELD_NAME_IDENTIFIER, assetId));
}

From source file:com.bewsia.script.LuceneHandler.java

License:Open Source License

protected void deleteEntity(String id) {
    if (id.length() == 0)
        return;/*from  ww w .j a  v  a 2  s . c  o  m*/
    String kind = "";

    try {
        IndexReader reader = IndexReader.open(FSDirectory.open(new File(dirIndex)));
        IndexSearcher searcher = new IndexSearcher(reader);
        TopDocs td = searcher.search(new TermQuery(new Term(SEntity.ID, id)), 1);
        if (td.totalHits > 0) {
            Document doc = searcher.doc(td.scoreDocs[0].doc);
            kind = doc.get(SEntity.KIND);
        }
        searcher.close();
        reader.close();
    } catch (Exception e) {
    }
    if (kind.length() == 0)
        return;
    if (!allowDelete(id, kind))
        return;

    try {
        if (!kind.equals(KIND_QUOTA)) {
            if (!quotaDelete(id, kind))
                return;
        }
        removeBackup(id, kind);
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
        IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36, analyzer);
        iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
        IndexWriter writer = new IndexWriter(FSDirectory.open(new File(dirIndex)), iwc);
        writer.deleteDocuments(new Term(SEntity.ID, id));
        writer.close();
    } catch (Exception e) {
    }
}

From source file:com.bugull.mongo.lucene.backend.IndexDeleteJob.java

License:Apache License

@Override
public void doJob() {
    String name = MapperUtil.getEntityName(clazz);
    IndexWriterHolder holder = IndexWriterHolder.getInstance();
    IndexWriter writer = holder.get(name);
    Term term = new Term(FieldsCache.getInstance().getIdFieldName(clazz), id);
    try {// ww  w .j  a  va 2s.  co m
        writer.deleteDocuments(term);
    } catch (CorruptIndexException ex) {
        logger.error("IndexWriter can not delete a document from the lucene index", ex);
    } catch (IOException ex) {
        logger.error("IndexWriter can not delete a document from the lucene index", ex);
    }
}

From source file:com.bugull.mongo.lucene.backend.IndexRemoveTask.java

License:Apache License

@Override
public void run() {
    String name = MapperUtil.getEntityName(clazz);
    IndexWriterCache cache = IndexWriterCache.getInstance();
    IndexWriter writer = cache.get(name);
    Term term = new Term(FieldsCache.getInstance().getIdFieldName(clazz), id);
    try {/*w ww. j  ava  2  s .co  m*/
        writer.deleteDocuments(term);
    } catch (CorruptIndexException ex) {
        logger.error("IndexWriter can not delete a document from the lucene index", ex);
    } catch (IOException ex) {
        logger.error("IndexWriter can not delete a document from the lucene index", ex);
    }
}

From source file:com.burkeware.search.api.internal.lucene.DefaultIndexer.java

License:Open Source License

/**
 * Delete an entry from the lucene index. The method will search for a single entry in the index (throwing
 * IOException when more than one index match the object).
 *
 * @param jsonObject  the json object to be deleted.
 * @param resource    the resource definition used to register the json to lucene index.
 * @param indexWriter the index writer used to delete the index.
 * @throws ParseException when the json can't be used to create a query to identify the correct lucene index.
 * @throws IOException    when other error happens during the deletion process.
 *//*from  www  .  ja  va  2 s .  c o  m*/
private void deleteObject(final Object jsonObject, final Resource resource, final IndexWriter indexWriter)
        throws ParseException, IOException {
    String queryString = createResourceQuery(resource) + " AND "
            + createSearchableFieldQuery(jsonObject, resource.getSearchableFields());

    if (getLogger().isDebugEnabled())
        getLogger().debug(this.getClass().getSimpleName(), "Query deleteObject(): " + queryString);

    Query query = parser.parse(queryString);
    List<Document> documents = findDocuments(query);
    if (!CollectionUtil.isEmpty(documents) && documents.size() > 1)
        throw new IOException("Unable to uniquely identify an object using the json object in the repository.");
    indexWriter.deleteDocuments(query);
}

From source file:com.codenvy.test.lucene.DeleteFilesWithSameName.java

License:Open Source License

public static void main(String[] args) throws Exception {
    String DOC_DIR_NAME = "files";
    filesDirPath = Paths.get(DOC_DIR_NAME).toAbsolutePath().toString();

    Path indexPath = Paths.get("index");
    Path docDir = Paths.get(DOC_DIR_NAME);

    Path file1 = Paths.get(DOC_DIR_NAME, "File1");
    Path file2 = Paths.get(DOC_DIR_NAME, "File1A");

    Analyzer analyzer = new SimpleAnalyzer();
    IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
    iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    //iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

    if (!Files.isReadable(docDir)) {
        System.out.println("document folder not found");
        return;//  ww w.j  ava  2  s  . c om
    }

    Directory index = FSDirectory.open(indexPath);

    IndexWriter writer = new IndexWriter(index, iwc);

    //add files to index
    indexDocs(writer, file1);
    indexDocs(writer, file2);
    writer.commit();

    searchAndPrintResult(indexPath);

    //delete files
    System.out.println();
    System.out.println("==================================================================");
    System.out.println("delete by prefix \"" + filesDirPath + "/File1\"");
    Query query = new PrefixQuery(new Term(PATH, filesDirPath + "/File1"));

    writer.deleteDocuments(query);
    writer.close();

    searchAndPrintResult(indexPath);
}

From source file:com.concursive.connect.indexer.LuceneIndexer.java

License:Open Source License

private boolean indexDeleteItem(IndexWriter writer, Object item, String deleteTerm) throws IOException {
    // Determine the object's indexer key term for deletion
    Indexer objectIndexer = (Indexer) getObjectIndexer(item.getClass().getName() + "Indexer");
    if (objectIndexer == null) {
        return false;
    }/*  ww  w  .ja  va  2s . com*/
    // Delete the previous item from the index
    Object o = null;
    try {
        // now we are ready for the next to last step..to call upon the method in the
        // class instance we have.
        Method method = objectIndexer.getClass().getMethod(deleteTerm, Object.class);
        o = method.invoke(objectIndexer, item);
    } catch (NoSuchMethodException nm) {
        LOG.error("No Such Method Exception for method " + deleteTerm + ". MESAGE = " + nm.getMessage(), nm);
    } catch (IllegalAccessException ia) {
        LOG.error("Illegal Access Exception. MESSAGE = " + ia.getMessage(), ia);
    } catch (Exception e) {
        LOG.error("Exception. MESSAGE = " + e.getMessage(), e);
    }
    if (o != null) {
        LOG.debug("Deleting with deleteTerm: " + deleteTerm);
        writer.deleteDocuments((Term) o);
    }
    return true;
}

From source file:com.docdoku.server.IndexerBean.java

License:Open Source License

@Asynchronous
@Lock(LockType.WRITE)/*from  ww w.  j a  v a2s  . c  om*/
public void removeFromIndex(String fullName) {
    IndexWriter indexWriter = null;
    Directory indexDir = null;
    try {
        indexDir = FSDirectory.open(new File(indexPath));
        indexWriter = new IndexWriter(indexDir, new StandardAnalyzer(Version.LUCENE_30),
                IndexWriter.MaxFieldLength.LIMITED);
        indexWriter.deleteDocuments(new Term("fullName", fullName));
    } catch (LockObtainFailedException ex) {
        try {
            if (IndexWriter.isLocked(indexDir)) {
                IndexWriter.unlock(indexDir);
            }
        } catch (IOException pIOEx) {
            throw new EJBException(pIOEx);
        }
        throw new EJBException(ex);
    } catch (CorruptIndexException ex) {
        throw new EJBException(ex);
    } catch (IOException ex) {
        throw new EJBException(ex);
    } finally {
        try {
            if (indexWriter != null) {
                indexWriter.close();
            }
        } catch (IOException ex) {
            throw new EJBException(ex);
        }
    }
}