2

Imagine, you have a MongoDB collection that maps to a simple entity in Spring Boot app:

@Document
data class Question(
    @Id val id: String,

    @TextIndexed
    val topic: String
)

Now you want to add a new field and include it in the full-text search. You make a simple modification:

@Document
data class Question(
    @Id val id: String,

    @TextIndexed
    val topic: String,

    @TextIndexed
    val description: String
)

To verify this change, you start the MongoDB database, start your app, fingers crossed, and BOOM!!! you get the following exception on init:

Caused by: org.springframework.dao.DataIntegrityViolationException:
    Cannot create index for '' in collection 'question' with keys 'Document{{topic=text, description=text}}' and options 'Document{{name=Question_TextIndex}}'. Index already defined as 'IndexInfo [indexFields=[IndexField [ key: topic, direction: null, type: TEXT, weight: 1.0]], name=Question_TextIndex, unique=false, sparse=false, language=english, partialFilterExpression=null, collation=null]'.;
nested exception is com.mongodb.MongoCommandException:
    Command failed with error 85: 'Index with name: Question_TextIndex already exists with different options' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "Index with name: Question_TextIndex already exists with different options", "code" : 85, "codeName" : "IndexOptionsConflict" }
...

It looks like Spring Data automatically creates a new text index that conflicts with the existing one by name. How to "tell" Spring Data that I need to modify (replace / alter) the existing index? Or maybe somehow create an index with a new name? What is a good way to resolve such conflicts in Spring Data?

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
  • this might help: https://titanwolf.org/Network/Articles/Article?AID=d008a59a-2374-4f05-9ea3-7424fb529e23#gsc.tab=0 – Ashish Aug 12 '21 at 18:30

1 Answers1

-1

To skip index creation in spring-data mongodb you may use auto-index creation flag as false,

you can try to put below property definition in under your property file :

  spring.data.mongodb.auto-index-creation: false
erhanasikoglu
  • 1,685
  • 1
  • 21
  • 33
  • 2
    if I skip index creation, I will have a DB using an outdated index. it doesn't make sense to me, because I can't test changes in the index then. I'm looking for ways to update (replace/alter) the existing index. – naXa stands with Ukraine Sep 21 '20 at 10:08
  • I got your point, but I'm afraid there is no direct recreate/alter way in spring-data. I would follow spring profiling in test environment and apply those steps : ensureIndex has been created, then drop it then recreate it (https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/index/IndexOperations.html) – erhanasikoglu Sep 21 '20 at 10:56