Kapil Earanky
Kapil Earanky

Reputation: 211

Unable to execute Spring-data Couchbase query

I've a spring-data couchbase repository. I'm trying to query the database using n1ql queries through the @Query annotation. A basic repository I implemented looks like this:

public interface CouchBaseRepository extends PagingAndSortingRepository<GsJsonStore, Long> {
@Query("SELECT * FROM default WHERE ?0 = ?1")
public Page<GsJsonStore> matchJson(String term, String value, Pageable pageable);�
}�

When I try to query using this method I get the error:

Unable to execute the query due to the following errors:
{"msg":"syntax error - at 0","code":3000}

Is there something I'm doing wrong?

Upvotes: 2

Views: 1063

Answers (2)

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

The syntax for inline query is plain N1QL, which uses $ instead of ?.

HOWEVER note that @Query with a handcrafted query isn't always the best idea, since it has caveats to write one.

In order to unmarshall the entity correctly, the query should also extract some metadata: the ID of the document (which becomes the entity's @Id) and the CAS (which becomes the entity's @Version)...

Also, since in Couchbase data of any type can be mixed in the same backing bucket, the query should always filter on the correct _class attribute.

So your query would be best rewritten using utility SpEL in order to take all that into consideration:

@Query("#n1ql.selectEntity WHERE $0 = $1 AND #n1ql.filter")

selectEntity will be replaced by the adequate "SELECT default.*, META(default).ID AS id, META(default).CAS AS cas FROM default". Similarly, filter will be replaced by the adequate where clause "_class = 'com.packege.here.GsJsonStore'".

Upvotes: 2

Kapil Earanky
Kapil Earanky

Reputation: 211

Replacing '?' with '$' fixed the issue.

Upvotes: 0

Related Questions