|
16 | 16 |
|
17 | 17 | package org.springframework.ai.model.chat.memory.repository.mongo.autoconfigure; |
18 | 18 |
|
| 19 | +import java.lang.reflect.Method; |
| 20 | + |
19 | 21 | import org.slf4j.Logger; |
20 | 22 | import org.slf4j.LoggerFactory; |
21 | 23 |
|
|
27 | 29 | import org.springframework.data.domain.Sort; |
28 | 30 | import org.springframework.data.mongodb.core.MongoTemplate; |
29 | 31 | import org.springframework.data.mongodb.core.index.Index; |
| 32 | +import org.springframework.data.mongodb.core.index.IndexDefinition; |
| 33 | +import org.springframework.data.mongodb.core.index.IndexOperations; |
30 | 34 |
|
31 | 35 | /** |
32 | 36 | * Class responsible for creating proper MongoDB indices for the ChatMemory. Creates a |
33 | | - * main index on the conversationId and timestamp fields, and a TTL index on the timestamp |
34 | | - * field if the TTL is set in properties. |
| 37 | + * main index on the conversationId and timestamp fields, and a TTL index on the |
| 38 | + * timestamp field if the TTL is set in properties. |
35 | 39 | * |
36 | 40 | * @author Łukasz Jernaś |
37 | 41 | * @see MongoChatMemoryProperties |
|
41 | 45 | @ConditionalOnProperty(value = "spring.ai.chat.memory.repository.mongo.create-indices", havingValue = "true") |
42 | 46 | public class MongoChatMemoryIndexCreatorAutoConfiguration { |
43 | 47 |
|
44 | | - private static final Logger logger = LoggerFactory.getLogger(MongoChatMemoryIndexCreatorAutoConfiguration.class); |
| 48 | + private static final Logger logger = LoggerFactory |
| 49 | + .getLogger(MongoChatMemoryIndexCreatorAutoConfiguration.class); |
45 | 50 |
|
46 | 51 | private final MongoTemplate mongoTemplate; |
47 | 52 |
|
48 | 53 | private final MongoChatMemoryProperties mongoChatMemoryProperties; |
49 | 54 |
|
50 | | - public MongoChatMemoryIndexCreatorAutoConfiguration(MongoTemplate mongoTemplate, |
51 | | - MongoChatMemoryProperties mongoChatMemoryProperties) { |
| 55 | + public MongoChatMemoryIndexCreatorAutoConfiguration(final MongoTemplate mongoTemplate, |
| 56 | + final MongoChatMemoryProperties mongoChatMemoryProperties) { |
52 | 57 | this.mongoTemplate = mongoTemplate; |
53 | 58 | this.mongoChatMemoryProperties = mongoChatMemoryProperties; |
54 | 59 | } |
55 | 60 |
|
| 61 | + /** |
| 62 | + * Initializes MongoDB indices after application context refresh. |
| 63 | + */ |
56 | 64 | @EventListener(ContextRefreshedEvent.class) |
57 | 65 | public void initIndicesAfterStartup() { |
58 | 66 | logger.info("Creating MongoDB indices for ChatMemory"); |
59 | 67 | // Create a main index |
60 | | - this.mongoTemplate.indexOps(Conversation.class) |
61 | | - .createIndex(new Index().on("conversationId", Sort.Direction.ASC).on("timestamp", Sort.Direction.DESC)); |
62 | | - |
| 68 | + createMainIndex(); |
63 | 69 | createOrUpdateTtlIndex(); |
64 | 70 | } |
65 | 71 |
|
| 72 | + private void createMainIndex() { |
| 73 | + var indexOps = this.mongoTemplate.indexOps(Conversation.class); |
| 74 | + var index = new Index().on("conversationId", Sort.Direction.ASC) |
| 75 | + .on("timestamp", Sort.Direction.DESC); |
| 76 | + |
| 77 | + // Use reflection to handle API differences across Spring Data MongoDB versions |
| 78 | + createIndexSafely(indexOps, index); |
| 79 | + } |
| 80 | + |
66 | 81 | private void createOrUpdateTtlIndex() { |
67 | 82 | if (!this.mongoChatMemoryProperties.getTtl().isZero()) { |
| 83 | + var indexOps = this.mongoTemplate.indexOps(Conversation.class); |
68 | 84 | // Check for existing TTL index |
69 | | - this.mongoTemplate.indexOps(Conversation.class).getIndexInfo().forEach(idx -> { |
| 85 | + indexOps.getIndexInfo().forEach(idx -> { |
70 | 86 | if (idx.getExpireAfter().isPresent() |
71 | | - && !idx.getExpireAfter().get().equals(this.mongoChatMemoryProperties.getTtl())) { |
| 87 | + && !idx.getExpireAfter().get() |
| 88 | + .equals(this.mongoChatMemoryProperties.getTtl())) { |
72 | 89 | logger.warn("Dropping existing TTL index, because TTL is different"); |
73 | | - this.mongoTemplate.indexOps(Conversation.class).dropIndex(idx.getName()); |
| 90 | + indexOps.dropIndex(idx.getName()); |
74 | 91 | } |
75 | 92 | }); |
76 | | - this.mongoTemplate.indexOps(Conversation.class) |
77 | | - .createIndex(new Index().on("timestamp", Sort.Direction.ASC) |
| 93 | + // Use reflection to handle API differences across Spring Data MongoDB |
| 94 | + // versions |
| 95 | + createIndexSafely(indexOps, new Index().on("timestamp", Sort.Direction.ASC) |
78 | 96 | .expire(this.mongoChatMemoryProperties.getTtl())); |
79 | 97 | } |
80 | 98 | } |
81 | 99 |
|
| 100 | + /** |
| 101 | + * Creates an index using reflection to handle API changes across different Spring |
| 102 | + * Data MongoDB versions: |
| 103 | + * <ul> |
| 104 | + * <li>Spring Data MongoDB 4.2.x - 4.4.x: only {@code ensureIndex(IndexDefinition)} |
| 105 | + * is available.</li> |
| 106 | + * <li>Spring Data MongoDB 4.5.x+: {@code createIndex(IndexDefinition)} is the new |
| 107 | + * API, {@code ensureIndex} is deprecated.</li> |
| 108 | + * </ul> |
| 109 | + * @param indexOps the IndexOperations instance |
| 110 | + * @param index the index definition |
| 111 | + * @throws IllegalStateException if neither method is available or invocation fails |
| 112 | + */ |
| 113 | + private void createIndexSafely(final IndexOperations indexOps, final IndexDefinition index) { |
| 114 | + try { |
| 115 | + // Try new API (Spring Data MongoDB 4.5.x+) |
| 116 | + Method method = IndexOperations.class.getMethod("createIndex", IndexDefinition.class); |
| 117 | + method.invoke(indexOps, index); |
| 118 | + logger.debug("Created index using createIndex() method"); |
| 119 | + } |
| 120 | + catch (NoSuchMethodException createIndexNotFound) { |
| 121 | + // Fall back to old API (Spring Data MongoDB 4.2.x - 4.4.x) |
| 122 | + try { |
| 123 | + Method method = IndexOperations.class.getMethod("ensureIndex", IndexDefinition.class); |
| 124 | + method.invoke(indexOps, index); |
| 125 | + logger.debug("Created index using ensureIndex() method"); |
| 126 | + } |
| 127 | + catch (NoSuchMethodException ensureIndexNotFound) { |
| 128 | + throw new IllegalStateException( |
| 129 | + "Neither createIndex() nor ensureIndex() method found on IndexOperations. " |
| 130 | + + "This may indicate an unsupported Spring Data MongoDB version.", |
| 131 | + ensureIndexNotFound); |
| 132 | + } |
| 133 | + catch (ReflectiveOperationException ex) { |
| 134 | + throw new IllegalStateException("Failed to invoke ensureIndex() method", ex); |
| 135 | + } |
| 136 | + } |
| 137 | + catch (ReflectiveOperationException ex) { |
| 138 | + throw new IllegalStateException("Failed to invoke createIndex() method", ex); |
| 139 | + } |
| 140 | + } |
| 141 | + |
82 | 142 | } |
0 commit comments