Skip to content

Commit 2fa15f7

Browse files
committed
Escape backslash in StringQuery.
Original Pull Request Closes #2326 (cherry picked from commit 03ecc48)
1 parent 02b6d54 commit 2fa15f7

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/main/java/org/springframework/data/elasticsearch/repository/support/StringQueryUtil.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,11 @@ public String replacePlaceholders(String input, ParameterAccessor accessor) {
4646

4747
String placeholder = Pattern.quote(matcher.group()) + "(?!\\d+)";
4848
int index = NumberUtils.parseNumber(matcher.group(1), Integer.class);
49-
result = result.replaceAll(placeholder, Matcher.quoteReplacement(getParameterWithIndex(accessor, index)));
49+
String replacement = Matcher.quoteReplacement(getParameterWithIndex(accessor, index));
50+
result = result.replaceAll(placeholder, replacement);
51+
// need to escape backslashes that are not escapes for quotes so that they are sent as double-backslashes
52+
// to Elasticsearch
53+
result = result.replaceAll("\\\\([^\"'])", "\\\\\\\\$1");
5054
}
5155
return result;
5256
}
@@ -56,7 +60,6 @@ private String getParameterWithIndex(ParameterAccessor accessor, int index) {
5660
Object parameter = accessor.getBindableValue(index);
5761
String parameterValue = "null";
5862

59-
// noinspection ConstantConditions
6063
if (parameter != null) {
6164

6265
parameterValue = convert(parameter);

src/test/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQueryUnitTests.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,18 @@ void shouldEscapeStringsInCollectionsQueryParameters() throws Exception {
129129
"{ 'bool' : { 'must' : { 'terms' : { 'name' : [\"hello \\\"Stranger\\\"\",\"Another string\"] } } } }");
130130
}
131131

132+
@Test // #2326
133+
@DisplayName("should escape backslashes in collection query parameters")
134+
void shouldEscapeBackslashesInCollectionQueryParameters() throws NoSuchMethodException {
135+
136+
final List<String> parameters = Arrays.asList("param\\1", "param\\2");
137+
List<String> params = new ArrayList<>(parameters);
138+
org.springframework.data.elasticsearch.core.query.Query query = createQuery("findByNameIn", params);
139+
140+
assertThat(query).isInstanceOf(StringQuery.class);
141+
assertThat(((StringQuery) query).getSource()).isEqualTo(
142+
"{ 'bool' : { 'must' : { 'terms' : { 'name' : [\"param\\\\1\",\"param\\\\2\"] } } } }");
143+
}
132144
private org.springframework.data.elasticsearch.core.query.Query createQuery(String methodName, Object... args)
133145
throws NoSuchMethodException {
134146

0 commit comments

Comments
 (0)