Aaron.Zhao
Aaron.Zhao

Reputation: 101

How to use Spring Data Elasticsearch @Query

When I use the following code as Spring docs said eclipse always show Syntax error on token.

public interface BookRepository extends ElasticsearchRepository<Book, String> {
@Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}")
Page<Book> findByName(String name,Pageable pageable);}

Upvotes: 1

Views: 3312

Answers (2)

Florian Courtial
Florian Courtial

Reputation: 930

Copy your JSON query (under "query": {, without the query tag).

Write @Query("") in your code and paste your copied query inside the quotes, your IDE will probably automatically escape the query.

Useful for long queries.

Upvotes: 0

Val
Val

Reputation: 217514

I suspect it doesn't like the query inside the @Query annotation. You need to escape the double quotes in your query.

public interface BookRepository extends ElasticsearchRepository<Book, String> {
@Query("{\"bool\" : {\"must\" : {\"field\" : {\"name\" : \"?0\"}}}}")
Page<Book> findByName(String name,Pageable pageable);}

That's a documentation bug, indeed. In their tests, however, we can find out that the doubles quotes must be escaped, since the double quote is a reserved delimiter character in Java.

Upvotes: 3

Related Questions