После длительного поиска, я думаю, что на данный момент это невозможно с помощью аннотаций, поэтому я создал программный способ управления этим сценарием.
создавая нормальный индекс и соединение индексировать
Сначала я определил объект, чтобы сопоставить структуру индекса.
public class CollectionDefinition {
private String id;
private String collectionName;
private LinkedHashMap<String, Sort.Direction> normalIndexMap;
private ArrayList<String> compoundIndexMap;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public LinkedHashMap<String, Sort.Direction> getNormalIndexMap() {
return normalIndexMap;
}
public void setNormalIndexMap(LinkedHashMap<String, Sort.Direction> normalIndexMap) {
this.normalIndexMap = normalIndexMap;
}
public ArrayList<String> getCompoundIndexMap() {
return compoundIndexMap;
}
public void setCompoundIndexMap(ArrayList<String> compoundIndexMap) {
this.compoundIndexMap = compoundIndexMap;
}
Коллекция Json будет выглядеть следующим образом
{
"collectionName" : "example",
"normalIndexMap" : {
"sessionId" : "ASC",
"hash" : "DESC"
},
"compoundIndexMap" : [
"{\"hash\":1,\"sessionId\":1,\"serverDate\":-1}",
"{\"sessionId\":1,\"serverDate\":-1}",
"{\"sessionId\":1,\"loginWasSuccessful\":1,\"loginDate\":-1}"
]}
Затем мы можем создать коллекцию и индексы
private List<IndexDefinition> createIndexList(Map<String, Sort.Direction> normalIndexMap) {
Set<String> keySet = normalIndexMap.keySet();
List<IndexDefinition> indexArray = new ArrayList<>();
for (String key : keySet) {
indexArray.add(new Index(key, normalIndexMap.get(key)).background());
}
return indexArray;
}
В результате один список индекса может быть использован для создания единого индекса поля
private void createIndexes(List<IndexDefinition> indexDefinitionList, MongoOperations mongoOperations, String collectionName) {
indexDefinitionList.forEach(indexDefinition -> mongoOperations.indexOps(collectionName).ensureIndex(indexDefinition));
}
Индекс соединения или многопрофильное индекс сложно, нам нужно создать DBObjects определить индекс
private List<DBObject> createCompountIndexList(List<String> compoundIndexStringMapList) {//NOSONAR IS IN USE
if (compoundIndexStringMapList == null || compoundIndexStringMapList.isEmpty())
return new ArrayList<>(); //NOSONAR
ObjectMapper mapper = new ObjectMapper();
List<DBObject> basicDBObjectList = new ArrayList<>();
for (String stringMapList : compoundIndexStringMapList) {
LinkedHashMap<String, Integer> parsedMap;
try {
parsedMap = mapper.readValue(stringMapList, new TypeReference<Map<String, Integer>>() {
});
BasicDBObjectBuilder dbObjectBuilder = BasicDBObjectBuilder.start();
Iterator it = parsedMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry indexElement = (Map.Entry) it.next();
dbObjectBuilder.add((String) indexElement.getKey(), indexElement.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
basicDBObjectList.add(dbObjectBuilder.get());
} catch (IOException e) {//NOSONAR I´m logging it, we can not do anything more here cause it is part of the db configuration settings that need to be correct
Logger.getLogger(JsonCollectionCreation.class).error("The compound index definition " + stringMapList + " is not correct it can not be mapped to LinkHashMap");
}
}
return basicDBObjectList;
}
И результат может быть использован для создания индекса в коллекции
private void createCompoundIndex(List<DBObject> compoundIndexList, MongoOperations mongoOperations, String collectionName) {
if (compoundIndexList.isEmpty()) return;
for (DBObject compoundIndexDefinition : compoundIndexList) {
mongoOperations.indexOps(collectionName).ensureIndex(new CompoundIndexDefinition(compoundIndexDefinition).background());
}
}
Похожий вопрос HTTP://stackoverflow.com/questions/23942469/create-index-in-correct-collection – Alex