Improve robustness and readability in CosmosDBFilterExpressionConverter
I would like to propose a small improvement to the CosmosDBFilterExpressionConverter to make it more robust and idiomatic.
The changes focus on: 1.Improving constructor robustness 2.Simplifying and clarifying the doKey method implementation
- Constructor Robustness Currently, the constructor directly collects the provided columns into a Map using Collectors.toMap.
package org.springframework.ai.vectorstore.cosmosdb;
class CosmosDBFilterExpressionConverter extends AbstractFilterExpressionConverter {
private Map<String, String> metadataFields;
CosmosDBFilterExpressionConverter(Collection<String> columns) {
this.metadataFields = columns.stream().collect(Collectors.toMap(Function.identity(),
Function.identity()));
}
Issues
If the input Collection
Proposed improvement Add Assert.notNull to fail fast on invalid input. Apply distinct() to safely ignore duplicate column names.
CosmosDBFilterExpressionConverter(Collection<String> columns) {
Assert.notNull(columns, "Columns must not be null");
this.metadataFields = columns.stream()
.distinct()
.collect(Collectors.toMap(Function.identity(), Function.identity()));
}
2.Refactoring doKey Method
The current implementation relies on an Optional.isPresent() check followed by Optional.get().
@Override
protected void doKey(Key key, StringBuilder context) {
String keyName = key.key();
Optional<String> metadataField = getMetadataField(keyName);
if (metadataField.isPresent()) {
context.append("c.metadata." + metadataField.get());
}
else {
throw new IllegalArgumentException(String.format("No metadata field %s has been configured",
keyName));
}
}
Problem: This pattern is more verbose and less idiomatic than modern Optional usage.
Proposed improvement: Use orElseThrow to clearly express that a missing metadata field is an exceptional case
@Override
protected void doKey(Key key, StringBuilder context) {
String keyName = key.key();
String field = getMetadataField(keyName)
.orElseThrow(() -> new IllegalArgumentException(
String.format("No metadata field %s has been configured", keyName)));
context.append("c.metadata.").append(field);
}
Benefits: Clearer control flow No unsafe use of Optional.get() Improved readability and maintainability
Action If these changes look reasonable, I would be happy to submit a Pull Request.