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:org.hibernate.search.backend.impl.lucene.works.DeleteWorkDelegate.java

License:Open Source License

public void performWork(LuceneWork work, IndexWriter writer) {
    final Class<?> entityType = work.getEntityClass();
    final Serializable id = work.getId();
    log.tracef("Removing %s#%s by query.", entityType, id);
    DocumentBuilderIndexedEntity<?> builder = workspace.getDocumentBuilder(entityType);

    BooleanQuery entityDeletionQuery = new BooleanQuery();

    Query idQueryTerm;//from w w  w.j  a  v  a2 s. c om
    if (isIdNumeric(entityType, builder)) {
        idQueryTerm = NumericFieldUtils.createExactMatchQuery(builder.getIdKeywordName(), id);
    } else {
        idQueryTerm = new TermQuery(builder.getTerm(id));
    }
    entityDeletionQuery.add(idQueryTerm, BooleanClause.Occur.MUST);

    Term classNameQueryTerm = new Term(DocumentBuilder.CLASS_FIELDNAME, entityType.getName());
    TermQuery classNameQuery = new TermQuery(classNameQueryTerm);
    entityDeletionQuery.add(classNameQuery, BooleanClause.Occur.MUST);

    try {
        writer.deleteDocuments(entityDeletionQuery);
    } catch (Exception e) {
        String message = "Unable to remove " + entityType + "#" + id + " from index.";
        throw new SearchException(message, e);
    }
}

From source file:org.hibernate.search.backend.impl.lucene.works.PurgeAllWorkDelegate.java

License:Open Source License

public void performWork(LuceneWork work, IndexWriter writer) {
    final Class<?> entityType = work.getEntityClass();
    log.tracef("purgeAll Lucene index using IndexWriter for type: %s", entityType);
    try {/*from ww  w.  j  a v  a2s . c o m*/
        Term term = new Term(DocumentBuilder.CLASS_FIELDNAME, entityType.getName());
        writer.deleteDocuments(term);
    } catch (Exception e) {
        throw new SearchException("Unable to purge all from Lucene index: " + entityType, e);
    }
}

From source file:org.hibernate.search.backend.impl.lucene.works.UpdateExtWorkDelegate.java

License:Open Source License

public void performWork(LuceneWork work, IndexWriter writer, IndexingMonitor monitor) {
    checkType(work);/*from w ww.  j  a  v a 2s . com*/
    final Serializable id = work.getId();
    try {
        if (idIsNumeric) {
            log.tracef("Deleting %s#%s by query using an IndexWriter#updateDocument as id is Numeric",
                    managedType, id);
            writer.deleteDocuments(NumericFieldUtils.createExactMatchQuery(builder.getIdKeywordName(), id));
            // no need to log the Add operation as we'll log in the delegate
            this.addDelegate.performWork(work, writer, monitor);
        } else {
            log.tracef("Updating %s#%s by id using an IndexWriter#updateDocument.", managedType, id);
            Term idTerm = new Term(builder.getIdKeywordName(), work.getIdInString());
            Map<String, String> fieldToAnalyzerMap = work.getFieldToAnalyzerMap();
            ScopedAnalyzer analyzer = builder.getAnalyzer();
            analyzer = AddWorkDelegate.updateAnalyzerMappings(workspace, analyzer, fieldToAnalyzerMap);
            writer.updateDocument(idTerm, work.getDocument(), analyzer);
        }
        workspace.notifyWorkApplied(work);
    } catch (Exception e) {
        String message = "Unable to update " + managedType + "#" + id + " in index.";
        throw new SearchException(message, e);
    }
    if (monitor != null) {
        monitor.documentsAdded(1l);
    }
}

From source file:org.hibernate.search.backend.lucene.work.impl.QueryBasedDeleteEntryLuceneWork.java

License:LGPL

@Override
protected long doDeleteDocuments(IndexWriter indexWriter, String tenantId, String id) throws IOException {
    return indexWriter
            .deleteDocuments(LuceneQueries.discriminatorMultiTenancyDeleteDocumentQuery(tenantId, id));
}

From source file:org.hibernate.search.backend.lucene.work.impl.QueryBasedUpdateEntryLuceneWork.java

License:LGPL

@Override
protected long doUpdateEntry(IndexWriter indexWriter, String tenantId, String id, LuceneIndexEntry indexEntry)
        throws IOException {
    indexWriter.deleteDocuments(LuceneQueries.discriminatorMultiTenancyDeleteDocumentQuery(tenantId, id));
    return indexWriter.addDocuments(indexEntry);
}

From source file:org.hibernate.search.backend.lucene.work.impl.TermBasedDeleteEntryLuceneWork.java

License:LGPL

@Override
protected long doDeleteDocuments(IndexWriter indexWriter, String tenantId, String id) throws IOException {
    return indexWriter.deleteDocuments(new Term(LuceneFields.idFieldName(), id));
}

From source file:org.hip.vif.core.search.AbstractVIFIndexer.java

License:Open Source License

protected void deleteEntryInIndex(final Term inTerm) throws IOException {
    final IndexWriter lWriter = getIndexWriter(false);
    lWriter.deleteDocuments(inTerm);
    lWriter.commit();// www . j a va 2 s  .c o m
}

From source file:org.imixs.workflow.plugins.jee.extended.LucenePlugin.java

License:Open Source License

/**
 * This method updates the search index for a collection of workitems.
 * /*  w w  w  .j  a v  a2 s.  c o  m*/
 * For each workitem the method test if it did match the conditions to be
 * added into the search index. If the workitem did not match the conditions
 * the workitem will be removed from the index.
 * 
 * The method loads the lucene index properties from the imixs.properties
 * file from the classpath. If no properties are defined the method
 * terminates.
 * 
 * 
 * @param worklist
 *            of ItemCollections to be indexed
 * @return - true if the update was successfull
 * @throws Exception
 */
public static boolean updateWorklist(Collection<ItemCollection> worklist) throws PluginException {

    IndexWriter awriter = null;
    // try loading imixs-search properties
    Properties prop = loadProperties();
    if (prop.isEmpty())
        return false;

    try {
        awriter = createIndexWriter(prop);

        // add workitem to search index....

        for (ItemCollection workitem : worklist) {
            // create term
            Term term = new Term("$uniqueid", workitem.getItemValueString("$uniqueid"));
            // test if document should be indexed or not
            if (matchConditions(prop, workitem))
                awriter.updateDocument(term, createDocument(prop, workitem));
            else
                awriter.deleteDocuments(term);

        }
    } catch (IOException luceneEx) {
        // close writer!
        logger.warning(" Lucene Exception : " + luceneEx.getMessage());

        throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
                "Unable to update search index", luceneEx);

    } finally {

        if (awriter != null) {
            logger.fine(" close writer");
            try {
                awriter.close();
            } catch (CorruptIndexException e) {
                throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
                        "Unable to update search index", e);
            } catch (IOException e) {
                throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
                        "Unable to update search index", e);
            }

        }
    }

    logger.fine(" update worklist successfull");
    return true;
}

From source file:org.imixs.workflow.plugins.jee.extended.LucenePlugin.java

License:Open Source License

/**
 * This method removes a single workitem from the search index.
 * //from w w  w.  j a  v  a 2 s  .  co m
 * @param uniqueID
 *            of the workitem to be removed
 * @throws PluginException
 */
public static void removeWorkitem(String uniqueID) throws PluginException {
    IndexWriter awriter = null;
    Properties prop = loadProperties();
    if (!prop.isEmpty()) {
        try {
            awriter = createIndexWriter(prop);
            Term term = new Term("$uniqueid", uniqueID);
            awriter.deleteDocuments(term);
        } catch (CorruptIndexException e) {
            throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
                    "Unable to remove workitem '" + uniqueID + "' from search index", e);
        } catch (LockObtainFailedException e) {
            throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
                    "Unable to remove workitem '" + uniqueID + "' from search index", e);
        } catch (IOException e) {
            throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
                    "Unable to remove workitem '" + uniqueID + "' from search index", e);
        }
    }
}

From source file:org.infoglue.cms.controllers.kernel.impl.simple.LuceneController.java

License:Open Source License

private void indexInformation(NotificationMessage notificationMessage) {
    try {//ww w .ja  v  a2  s.c  o  m
        //Object objectIdentity = getObjectIdentity(object);

        IndexWriter writer = null;
        try {
            String index = CmsPropertyHandler.getContextRootPath() + File.separator + "lucene" + File.separator
                    + "index";

            File INDEX_DIR = new File(index);
            writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(new String[] {}));
            writer.setMaxMergeDocs(500000);
            if (logger.isInfoEnabled())
                logger.info("Indexing to directory '" + INDEX_DIR + "'...");

            if (notificationMessage.getType() == NotificationMessage.TRANS_CREATE) {
                List<Document> documents = getDocuments(notificationMessage);
                Iterator<Document> documentsIterator = documents.iterator();
                while (documentsIterator.hasNext()) {
                    Document indexingDocument = documentsIterator.next();
                    String uid = indexingDocument.get("uid");
                    if (logger.isInfoEnabled())
                        logger.info("Adding document with uid:" + uid + " - " + indexingDocument);
                    if (indexingDocument != null)
                        writer.addDocument(indexingDocument);
                }
            } else if (notificationMessage.getType() == NotificationMessage.TRANS_UPDATE) {
                List<Document> documents = getDocuments(notificationMessage);
                Iterator<Document> documentsIterator = documents.iterator();
                while (documentsIterator.hasNext()) {
                    Document indexingDocument = documentsIterator.next();
                    String uid = indexingDocument.get("uid");
                    if (logger.isInfoEnabled())
                        logger.info("Updating document with uid:" + uid + " - " + indexingDocument);
                    if (indexingDocument != null)
                        writer.updateDocument(new Term("uid", "" + uid), indexingDocument);
                }
            } else if (notificationMessage.getType() == NotificationMessage.TRANS_DELETE) {
                String uid = "";
                if (notificationMessage.getClassName().equals(ContentImpl.class.getName())) {
                    uid = "contentId_" + notificationMessage.getObjectId();
                } else if (notificationMessage.getClassName().equals(ContentVersionImpl.class.getName())) {
                    uid = "contentVersionId_" + notificationMessage.getObjectId();
                } else if (notificationMessage.getClassName().equals(DigitalAssetImpl.class.getName())) {
                    uid = "digitalAssetId_" + notificationMessage.getObjectId();
                }

                if (logger.isInfoEnabled())
                    logger.info("Deleting documents:" + "uid=" + uid);
                writer.deleteDocuments(new Term("uid", "" + uid));
            }
        } catch (Exception e) {
            logger.error("Error indexing:" + e.getMessage(), e);
        } finally {
            indexedDocumentsSinceLastOptimize++;
            if (indexedDocumentsSinceLastOptimize > 250) {
                logger.info("Optimizing...");
                writer.optimize();
                indexedDocumentsSinceLastOptimize = 0;
            }
            writer.close();
        }
    } catch (Exception e) {
        logger.error("Error indexing:" + e.getMessage(), e);
    }
}