Transaction support

picturesafe-search-enterprise supports the spring transaction management out-of-the-box. In an active transaction, all Elasticsearch index write requests (add, update or delete documents) will be bound to the transaction. Index changes will only be processed on a transaction commit, and on a transaction rollback the Elasticsearch index remains unchanged.

To use the transaction support, please make sure that the TransactionWriteRequestHandler class is available as a bean in the spring context. If you use the suggested spring configuration, the bean should be available automatically because of the configured component scan.

Here is some test code to show how the transaction support works:

@Test
public void testAddCommitSingle() {
    TransactionStatus transactionStatus 
            = transactionManager.getTransaction(new DefaultTransactionDefinition());
    elasticsearchService.addToIndex(indexAlias, 
            DataChangeProcessingMode.BLOCKING, DocumentBuilder.id(151).build());
    assertNull("Document should not have been written to index yet!", 
            elasticsearchService.getDocument(indexAlias, 151));

    transactionManager.commit(transactionStatus);
    assertNotNull("Document should have been written to index after commit!", 
            elasticsearchService.getDocument(indexAlias, 151));
}

@Test
public void testAddRollbackSingle() {
    TransactionStatus transactionStatus 
            = transactionManager.getTransaction(new DefaultTransactionDefinition());
    elasticsearchService.addToIndex(indexAlias, 
            DataChangeProcessingMode.BLOCKING, DocumentBuilder.id(151).build());
    transactionManager.rollback(transactionStatus);
    assertNull("Document should not have been written to index after rollback!", 
            elasticsearchService.getDocument(indexAlias, 151));
}