问题
I am using Elastic Search with Spring Data .
I have a simple method in repository:
findByUserNameContaining("a b");
This method not giving expecting result because of SPACE.
Error getting:
"Cannot constructQuery '"a b"'. Use expression or multiple clauses instead." EXCEPTION="org.springframework.dao.InvalidDataAccessApiUsageException: Cannot constructQuery '"a b"'. Use expression or multiple clauses instead.
For stopping creation of multiple tokens because of Space. I have mapping:
"userName": {
"type": "string",
"index": "not_analyzed"
},
I am totally surprised that I am getting this issue after "index": "not_analyzed"
in mapping .
Please help me. Thanks in advance!
回答1:
Actually Spring data apis (containing or startWith) does not work with space in String . I have implemented same with Elastic core api.
NativeSearchQueryBuilder aNativeSearchQueryBuilder = new NativeSearchQueryBuilder();
aNativeSearchQueryBuilder.withIndices(indexName).withTypes(type);
final BoolQueryBuilder aQuery = new BoolQueryBuilder();
aQuery.must(QueryBuilders.queryStringQuery("a b").defaultField("UserName"));
NativeSearchQuery nativeSearchQuery = aNativeSearchQueryBuilder.withQuery(aQuery).build();
List<Object> aDatas = elasticsearchTemplate.queryForList(nativeSearchQuery, Object.class);
回答2:
You have to mask the spaces:
findByUserNameContaining("a\\ b");
来源:https://stackoverflow.com/questions/43182552/spring-data-api-containing-or-startwith-not-working-with-space-which-has-wildc