2

I have a repository method that does a "starts with" (prefix) query on field userAccount.userName. When I search for string without space, it returns proper results. But when I search for strings with space in it, it throws an exception.

My repository method:

public List<EsUser> findByUserAccountUserNameStartingWith(String term);

Search String: Tom Cruise

Exception:

org.springframework.dao.InvalidDataAccessApiUsageException: Cannot constructQuery '*"Tom Cruise"'. Use expression or multiple clauses instead.

arun
  • 10,685
  • 6
  • 59
  • 81
Vijay Mohan
  • 1,056
  • 14
  • 34

1 Answers1

2

Queries against elasticsearch that use wildcards (e.g. *) must be a single token. By default, tokens are split by white space. "Tom Cruise" is two tokens.

If you need to include multiple tokens, consider implementing a custom Spring Data ES repository and use the following Elasticsearch API QueryBuilder. Something like this:

NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

QueryBuilder matchPhraseQuery = QueryBuilders.matchPhrasePrefixQuery("userName", "Tom Cruise");

QueryBuilder nestedQuery = QueryBuilders.nestedQuery("userAccount", matchPhraseQuery);

nativeSearchQueryBuilder.withQuery(nestedQuery);

NativeSearchQuery nativeSearchQuery = nativeSearchQueryBuilder.build();

//auto wire elastic search template
FacetedPage<EsUser> results = template.queryForPage(nativeSearchQuery, EsUser.class);
B.Coker
  • 71
  • 1
  • 5