Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Elastic Search with special characters

As part of our project we are using Spring Data on top of Elastic Search. We found very interesting issue with findBy queries. If we pass string that contains space it didn't find the right element unless we pad the string with quotes. For example: for getByName(String name) we should pass getByName("\"John Do\""). Is there any way to eliminate such redundant padding?

like image 283
Moshe Avatar asked Nov 10 '22 06:11

Moshe


1 Answers

I'm trying my first steps with Spring (Boot Starter) Data ES and stumbled upon the same issue as you have, only in my case it was a : that 'messed things up'. I've learned that this is part of the reserved characters (https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters). The quoting that you mention is exactly the solution I use for now. It results in a query like this:

{ "from": 0, "query": { "bool": { "must": { "query_string": { "query": "\"John Do\"", "fields": ["name"] } } } } }

(You can use this in a rest console or in ElasticHQ to check the result.) A colleague suggested that switching to a 'term' query:

{ "from": 0, "size": 100, "query": { "term" : { "name": "John Do"
} } }

might help to avoid the quoting. I have tried this out by use of the @Query annotation on the method findByName in your repository. It would go something like this:

@Query(value = "{\"term\" : {\"name\" : \"?0\"}}")
List<Person> findByName(String name);
like image 85
Wivani Avatar answered Nov 15 '22 10:11

Wivani