Search code examples
javaspringmongodbspring-bootcompound-index

How to update or drop @CompoundIndex with Spring


I have existing @CompoundIndex defined like:

@CompoundIndex(name = "idx_test_search", unique = true,
        def = "{type: 1, origin: 1, date: 1}")

And now i need to changed it to add another field like:

@CompoundIndex(name = "idx_test_search", unique = true,
        def = "{type: 1, origin: 1, date: 1, travelers: 1}")

I expected this to be applied automatically like it was created on app start, but in the MongoDb it remains the same old one. I can create a different index with new name but then I need to drop this one. Can I do it with @ChangeSet? Any ideas?


Solution

  • I managed to this with mongoTemplate and @Changeset:

    @ChangeLog(order = "0.0.1")
    public class MongoChangelogVersion_0_0_1 {
    
        @ChangeSet(order = "0001", id = "testSearchIndex", author = "djordje.ivanovic@****.com")
        public void dropIndex(MongoTemplate mongoTemplate) throws IOException {
            List<IndexInfo> indexes =  mongoTemplate.indexOps(TestSearch.class).getIndexInfo();
            for(IndexInfo indexInfo: indexes){
                if(indexInfo.getName().equals("idx_test_search")){
                    mongoTemplate.indexOps(TestSearch.class).dropIndex("idx_test_search");
                    break;
                }
            }
        }
    }
    

    mongoTemplate.indexOps(TestSearch.class) is returning a list of all indexes for related table (TestSearch in my case), so after checking if index exists, we will drop it.