我使用@Query
注释在我的Elastic Search存储库中实现了一个查询。查询中的一个字段是String,我发现当我尝试使用带有双引号的参数执行查询时,查询无法解析。
ElasticsearchStringQuery:88
类似乎只是将参数值替换为字符串查询而不转义参数中的可能引号。我做错了什么或者这只是一个已知的限制?如果已知,则在对存储库执行finder方法之前,调用者必须转义参数中的引号似乎很奇怪。这会导致我的代码被双引号剥离或转义乱丢,并且它会在外部泄漏查询格式(即双引号用于定义查询,因此不能在参数中使用)。
示例查询:
@Query("{ \"filtered\" : { \"query\" : { \"bool\" : { \"must\" : [ { \"match\" : { \"programTitle\" : { \"query\" : \"?0\", \"type\" : \"boolean\", \"operator\" : \"AND\", \"fuzziness\" : \"0\" } } }, { \"match\" : { \"title\" : { \"query\" : \"?2\", \"type\" : \"boolean\", \"operator\" : \"AND\",\"fuzziness\" : \"0\" } } } ] } }, \"filter\" : { \"term\" : { \"programAirDate\" : \"?1\" } } }}")
正在使用测试用例执行查询:
repository.save(piece);
List<Piece> actual = repository.findByProgramTitleAndProgramAirDateAndTitle(
piece.getProgramTitle(),
airDate.format(DateTimeFormatter.ISO_INSTANT),
piece.getTitle(), new PageRequest(0, 1));
如果piece.getTitle()
包含双引号,例如 Franz Joseph Haydn:String Quartet No. 53“The Lark”,则查询失败并显示错误:
at [Source: [B@1696066a; line: 1, column: 410]]; }{[7x1Q86yNTdy0a0zHarqYVA][metapub][4]: SearchParseException[[metapub][4]: from[0],size[1]: Parse Failure [Failed to parse source [{"from":0,"size":1,"query_binary":"eyAgImZpbHRlcmVkIiA6IHsgICAgInF1ZXJ5IiA6IHsgICAgICAiYm9vbCIgOiB7ICAgICAgICAibXVzdCIgOiBbIHsgICAgICAgICAgIm1hdGNoIiA6IHsgICAgICAgICAgICAicHJvZ3JhbVRpdGxlIiA6IHsgICAgICAgICAgICAgICJxdWVyeSIgOiAiQmVzdCBQcm9ncmFtIEV2ZXIiLCAgICAgICAgICAgICAgInR5cGUiIDogImJvb2xlYW4iLCAgICAgICAgICAgICAgIm9wZXJhdG9yIiA6ICJBTkQiLCAgICAgICAgICAgICAgImZ1enppbmVzcyIgOiAiMCIgICAgICAgICAgICB9ICAgICAgICAgIH0gICAgICAgIH0sIHsgICAgICAgICAgIm1hdGNoIiA6IHsgICAgICAgICAgICAidGl0bGUiIDogeyAgICAgICAgICAgICAgInF1ZXJ5IiA6ICJGcmFueiBKb3NlcGggSGF5ZG46IFN0cmluZyBRdWFydGV0IE5vLiA1MyAiVGhlIExhcmsiIiwgICAgICAgICAgICAgICJ0eXBlIiA6ICJib29sZWFuIiwgICAgICAgICAgICAgICJvcGVyYXRvciIgOiAiQU5EIiwgICAgICAgICAgICAgICJmdXp6aW5lc3MiIDogIjAiICAgICAgICAgICAgfSAgICAgICAgICB9ICAgICAgICB9IF0gICAgICB9ICAgIH0sICAgICJmaWx0ZXIiIDogeyAgICAgICJ0ZXJtIiA6IHsgICAgICAgICJwcm9ncmFtQWlyRGF0ZSIgOiAiMjAxNi0wNC0wMVQxMzowMDowMFoiICAgICAgfSAgICB9ICB9fQ=="}]]];
nested: QueryParsingException[[metapub] Failed to parse]; nested: JsonParseException[Unexpected character ('T' (code 84)): was expecting comma to separate OBJECT entries
解码base64查询我可以看到双引号导致问题:
... "title" : { "query" : "Franz Joseph Haydn: String Quartet No. 53 "The Lark"", "type" : "boolean", "operator" : "AND", ...
我可以通过删除所有双引号(例如,piece.getTitle().replaceAll("\"", "")
)来使事情有效,但这似乎是框架应该处理的事情。使用JDBC存储库时,用户不必删除/替换特殊字符,因为JDBC驱动程序会自动执行此操作。
那么处理这个问题的最佳方法是什么?