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:net.hillsdon.reviki.search.impl.LuceneSearcher.java

License:Apache License

private void deleteDocument(final String keyField, final String value) throws IOException {
    IndexWriter writer = new IndexWriter(_dir, createAnalyzer());
    try {/*from  w  w  w  . j a va2s  .c  o m*/
        writer.deleteDocuments(new Term(keyField, value));
    } finally {
        writer.close();
    }
}

From source file:net.hillsdon.reviki.search.impl.LuceneSearcher.java

License:Apache License

private void replaceDocument(final String keyField, final Document document)
        throws CorruptIndexException, LockObtainFailedException, IOException {
    IndexWriter writer = new IndexWriter(_dir, createAnalyzer());
    try {/*from w  ww  . j  ava2  s .  co  m*/
        writer.deleteDocuments(new Term(keyField, document.get(keyField)));
        writer.addDocument(document);
        writer.optimize();
    } finally {
        writer.close();
    }
}

From source file:net.oneandone.pommes.model.Database.java

License:Apache License

public void remove(List<String> prefixes) throws IOException {
    IndexWriter writer;
    IndexWriterConfig config;//from w w w  . jav a2 s .  c o m

    close();
    config = new IndexWriterConfig(Version.LUCENE_4_9, null);
    config.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    writer = new IndexWriter(getIndexLuceneDirectory(), config);
    for (String prefix : prefixes) {
        writer.deleteDocuments(new PrefixQuery(new Term(ORIGIN, prefix)));
    }
    writer.close();
}

From source file:net.sf.lucis.core.impl.DefaultWriter.java

License:Apache License

public <T, P> IndexStatus write(Store<T> store, Batch<T, P> batch) throws InterruptedException {
    Preconditions.checkNotNull(store, "A destination store must be provided.");
    if (batch == null) {
        return null;
    }// w w w  .  jav  a  2s  . c o m
    try {
        final IndexWriterConfig config = config();
        final T oldCP = store.getCheckpoint();
        final T newCP = batch.getCheckpoint();
        if (Objects.equal(oldCP, newCP)) {
            return null;
        }
        throwIfInterrupted();
        if (!batch.isEmpty()) {
            final Analyzer analyzer = config.getAnalyzer();
            // Check whether the index must be created
            final Directory directory = store.getDirectory();
            config.setOpenMode(batch.isRecreate() ? OpenMode.CREATE : OpenMode.CREATE_OR_APPEND);
            final IndexWriter writer = new IndexWriter(directory, config);
            boolean ok = false;
            try {
                // Deletions
                if (!batch.isRecreate()) {
                    for (Term term : batch.getDeletions()) {
                        throwIfInterrupted();
                        writer.deleteDocuments(term);
                    }
                }
                // Additions
                for (Addition addition : batch.getAdditions()) {
                    throwIfInterrupted();
                    final Analyzer aa = addition.getAnalyzer();
                    writer.addDocument(addition.getDocument(), aa != null ? aa : analyzer);
                }
                // Commit
                throwIfInterrupted();
                writer.commit();
                ok = true;
                // No optimize until policy is defined.
                // writer.optimize();
            } finally {
                if (!ok) {
                    rollback(writer);
                }
                writer.close();
            }
        }
        store.setCheckpoint(newCP);
        return IndexStatus.OK;
    } catch (InterruptedException ie) {
        throw ie;
    } catch (LockObtainFailedException le) {
        log().error(le, "Unable to lock index");
        return IndexStatus.LOCKED;
    } catch (CorruptIndexException ce) {
        log().error(ce, "Corrupt index");
        return IndexStatus.CORRUPT;
    } catch (IOException ioe) {
        log().error(ioe, "I/O Error while writing");
        return IndexStatus.IOERROR;
    } catch (Exception e) {
        log().error(e, "Exception while writing");
        return IndexStatus.ERROR;
    }
}

From source file:net.sf.mmm.search.indexer.impl.lucene.LuceneSearchIndexer.java

License:Apache License

/**
 * This method performs the actual remove by {@link Term}.
 *
 * @see #removeByCustumId(String)/*from   www .  ja  v a 2 s  .com*/
 * @see #removeByUri(String, String)
 * @see IndexWriter#deleteDocuments(Term)
 *
 * @param term is the {@link Term} identifying the {@link SearchEntry entry/entries} to remove.
 * @return the number of removed {@link SearchEntry entries}.
 */
protected int remove(Term term) {

    try {
        IndexWriter writer = getIndexWriter();
        int count = writer.getReader().docFreq(term);
        if (count > 0) {
            writer.deleteDocuments(term);
        }
        return count;
    } catch (IOException e) {
        throw new SearchRemoveFailedException(e, term.field(), term.text());
    }
}

From source file:net.simpleframework.ado.lucene.AbstractLuceneManager.java

License:Apache License

@Override
public void doDeleteIndex(final Object... objects) {
    IndexWriter iWriter = null;
    try {/*from  w w w .j a  v  a 2  s.c  om*/
        iWriter = createIndexWriter();
        for (final Object obj : objects) {
            final String id = getId(obj);
            if (StringUtils.hasText(id)) {
                iWriter.deleteDocuments(new Term("id", id));
            }
        }
    } catch (final IOException e) {
        throw ADOException.of(e);
    } finally {
        closeWriter(iWriter);
    }
}

From source file:net.tooan.ynpay.third.mongodb.lucene.backend.IndexRemoveTask.java

License:Apache License

@Override
public void run() {
    String[] name = MapperUtil.getEntityName(clazz);
    IndexWriterCache cache = IndexWriterCache.getInstance();
    IndexWriter writer = cache.get(StringUtils.join(name, "."));
    Term term = new Term(FieldsCache.getInstance().getIdFieldName(clazz), id);
    try {//ww w  .ja  va 2 s.c om
        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:net.ymate.platform.module.search.Searchs.java

License:Apache License

public static void indexRemove(final Class<? extends ISearchable> searchableClass, final String id,
        final ICallbackHandler handler) {
    __doCheckModuleInited();/*from w w w  .j  ava 2s .com*/
    __executor.execute(new Runnable() {

        public void run() {
            IndexedMeta _meta = getIndexedMeta(searchableClass);
            IndexWriter _writer = getIndexWriter(_meta.getIndexName());
            Term term = new Term(IndexedMeta.FIELD_ID, id);
            try {
                _writer.deleteDocuments(term);
                if (handler != null) {
                    handler.onIndexRemoved(searchableClass, id);
                }
            } catch (IOException ex) {
                _LOG.error("IndexWriter Delete Document Error:", ex);
            }
        }
    });
}

From source file:nl.strohalm.cyclos.utils.lucene.IndexOperationRunner.java

License:Open Source License

private boolean rebuildMemberAds(final Long userId, final Analyzer analyzer, final Session session) {
    final Class<? extends Indexable> entityType = Ad.class;
    final IndexWriter writer = getWriter(entityType);
    boolean success = false;

    DocumentMapper documentMapper = indexHandler.getDocumentMapper(entityType);
    try {/*from   w  w w .jav  a 2 s  . c  o m*/
        writer.deleteDocuments(new Term("owner", userId.toString()));
    } catch (CorruptIndexException e) {
        handleIndexCorrupted(entityType);
        success = false;
    } catch (IOException e) {
        LOG.error("Error while reindexing a member's advertisements", e);
        success = false;
    }

    ScrollableResults scroll = session
            .createQuery("from Ad a where a.deleteDate is null and a.owner.id = " + userId)
            .scroll(ScrollMode.FORWARD_ONLY);

    try {
        int index = 0;
        while (scroll.next()) {
            Indexable entity = (Indexable) scroll.get(0);
            Document document = documentMapper.map(entity);
            try {
                writer.addDocument(document, analyzer);
            } catch (CorruptIndexException e) {
                handleIndexCorrupted(entityType);
                success = false;
                break;
            } catch (IOException e) {
                LOG.error("Error while adding advertisements to index", e);
                success = false;
                break;
            }
            // Every batch, clear the session and commit the writer
            if (++index % 30 == 0) {
                session.clear();
            }
        }
        success = true;
    } finally {
        scroll.close();
    }

    // Finish the writer operation
    if (success) {
        commit(entityType, writer);
        return true;
    } else {
        rollback(entityType, writer);
        return false;
    }
}

From source file:nl.strohalm.cyclos.utils.lucene.IndexOperationRunner.java

License:Open Source License

private boolean rebuildMemberRecords(final Long userId, final Analyzer analyzer, final Session session) {
    final Class<? extends Indexable> entityType = MemberRecord.class;
    final IndexWriter writer = getWriter(entityType);
    boolean success = false;

    DocumentMapper documentMapper = indexHandler.getDocumentMapper(entityType);
    try {/*from ww  w.j a  va 2  s.c  o  m*/
        writer.deleteDocuments(new Term("element", userId.toString()));
    } catch (CorruptIndexException e) {
        handleIndexCorrupted(entityType);
        success = false;
    } catch (IOException e) {
        LOG.error("Error while reindexing an user's records", e);
        success = false;
    }

    ScrollableResults scroll = session.createQuery("from MemberRecord mr where mr.element.id = " + userId)
            .scroll(ScrollMode.FORWARD_ONLY);

    try {
        int index = 0;
        while (scroll.next()) {
            Indexable entity = (Indexable) scroll.get(0);
            Document document = documentMapper.map(entity);
            try {
                writer.addDocument(document, analyzer);
            } catch (CorruptIndexException e) {
                handleIndexCorrupted(entityType);
                success = false;
                break;
            } catch (IOException e) {
                LOG.error("Error while adding member records to index", e);
                success = false;
                break;
            }
            // Every batch, clear the session and commit the writer
            if (++index % 30 == 0) {
                session.clear();
            }
        }
        success = true;
    } finally {
        scroll.close();
    }

    // Finish the writer operation
    if (success) {
        commit(entityType, writer);
        return true;
    } else {
        rollback(entityType, writer);
        return false;
    }
}