BulkRequestBuilder bulkRequestBuilder = elasticSearchClient.prepareBulk();
//bulkRequestBuilder.setRefresh(true);
// Execute index requests
for (Map.Entry<IndexEntityKey, Object> entry : toIndex.entrySet()) {
SearchableClassMapping scm = elasticSearchContextHolder.getMappingContextByType(entry.getKey().getClazz());
if (isNewSession) {
persistenceInterceptor = createInterceptor();
session = SessionFactoryUtils.getSession(sessionFactory, true);
}
try {
Object entity = entry.getValue();
// If this not a transient instance, reattach it to the session
if (session.contains(entity)) {
session.lock(entity, LockMode.NONE);
LOG.debug("Reattached entity to session");
}
XContentBuilder json = toJSON(entity);
bulkRequestBuilder.add(
elasticSearchClient.prepareIndex()
.setIndex(scm.getIndexName())
.setType(scm.getElasticTypeName())
.setId(entry.getKey().getId()) // TODO : Composite key ?
.setSource(json)
);
if (LOG.isDebugEnabled()) {
try {
LOG.debug("Indexing " + entry.getKey().getClazz() + "(index:" + scm.getIndexName() + ",type:" + scm.getElasticTypeName() +
") of id " + entry.getKey().getId() + " and source " + json.string());
} catch (IOException e) {
}
}
} finally {
if (null != persistenceInterceptor) {
persistenceInterceptor.destroy();
}
}
}
// Execute delete requests
for (IndexEntityKey key : toDelete) {
SearchableClassMapping scm = elasticSearchContextHolder.getMappingContextByType(key.getClazz());
if (LOG.isDebugEnabled()) {
LOG.debug("Deleting object from index " + scm.getIndexName() + " and type " + scm.getElasticTypeName() + " and ID " + key.getId());
}
bulkRequestBuilder.add(
elasticSearchClient.prepareDelete()
.setIndex(scm.getIndexName())
.setType(scm.getElasticTypeName())
.setId(key.getId())
);
}
// Perform bulk request