问题
I have a entity Person, inherited by Musician and Politician and a repository PersonRepository.
I am trying to have all three entities saved into the a collection "person" in MongoDB using PersonRepository.save(..) default method but somehow, Spring-Data-MongoDB save it into 3 separate collections "person", "musician" and "politician".
Java Code:
@Document
public class Person {
@Id private String id;
@Indexed private String name;
@TextIndexed private String biography;
}
@Document
public Musician extends Person {
private String something;
}
@Document
public Politician extends Person {
private String somethingElse;
}
@Repository
public interface PersonRepository extends CrudRepository<User, String> {
}
After reading some posts saying I have to set the collection name into the annotation @Document(collection = "person") for all three of the entity for the repository to save it into a same collection.
It works well but when I check the Indexes in MongoDB, somehow I get the TextIndex being named after the last entity class which is saved.
It seems that TextIndex will always being named after the entity class name being saved, and not the collection name which I have set in the document annotation.
MongoDB Shell:
db.person.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.person"
},
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "Musician_TextIndex",
"ns" : "test.person",
"weights" : {
"description" : 1,
"name" : 10
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]
Is there any way I could set the TextIndex name instead of naming it after the entity class which I am saving. Tried to search could find any.
回答1:
Currently there is no way of setting the index name for TextIndex
using the annotation based setup. To do so please use the IndexOperations
via the template
to set up the text index manually.
template.indexOps(Person.class)
.ensureIndex(
new TextIndexDefinitionBuilder()
.named("YourIndexNameHere")
.onField("biography")
.build());
来源:https://stackoverflow.com/questions/39377546/how-to-set-textindex-name-in-an-entity-with-spring-data-mongodb