Search code examples
spring-bootelasticsearchspring-data-jpaspring-dataspring-data-elasticsearch

How to matches any character on elasticsearch request with Spring-Boot and JPA?


I want to match any character against two characters "*" and "?" in the parameters of a query using JPA and an elasticsearch database.

Example:

In my database I have a "code" String: "AA33BB", "AA38BB", "CG77FF", "DV11PL"...

I wish to receive the first 100 results with the parameter "AA*" to obtain as an answer => "AA33BB", "AA38BB".

But also receive the first 100 results with the parameter "AA3?BB" or "AA??BB" (? in any place) to obtain as an answer => "AA33BB", "AA38BB".

I'm using Java Spring-Boot 3 with elasticsearch dependency:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

//////////////////////// My repository:

@Repository
public interface CodeRepository extends ElasticsearchRepository<Code, Long> {

     Iterable<Code> findFirst100CodeContaining(String code);

}

//////////////////// My service:

@Service
public classServiceCode {

@Autowired
     private CodeRepository codeRepository;

public Iterable<CodeDTO> searchCodes(CodeDTO CodeDTO) {
         String code = codeDTO.getCode();
         code = code.replace("?", ".");
         code = code.replace("*", "");
         Iterable<Code> codeList = codeRepository.findFirst100ByCodeContaining(code);
         return mapToListOfDTO(codeList);
     }
}

The SQL version query: @Query("SELECT c FROM codes c WHERE c.code LIKE:code")

It works for "*" but not for "?".

Do you have an idea of the character to replace or how to do otherwise?


Solution

  • I found the answer it was enough to pass the parameters in this way:

    @Query("{\"bool\": {\"must\": [{\"match\": {\"wildcard\": {\"code\": {\"value\": \"?1\"}}}]}}")
    

    It works !