Writing dynamic n1ql query with spring data 4.x

I am migrating/upgrading to spring data couchbase 4.x

I am currently using n1Ql query in String.
SimpleN1qlQuery n1qlQuery = N1qlQuery.simple(“n1QlqueryString”);
couchbaseTemplate.findByN1QL(n1qlQuery, Model.class);

With upgrade, i don’t see a way to create Query from stringQuery in spring data. Is there a way to do that. I can not use sdk query directly instead of using spring data dynamic query as i need to have custom JsonSerializer to parse the result, which Java sdk can not do that.

How can create Query from String using spring data. Thank you for the help!!

The only support for dynamically created string queries in 4.x is to use the couchbase java sdk through template.getCouchbaseClientFactory().
The alternative is to use the matching(queryObj) method on the template.
I’m currently working on implementing querydsl for an upcoming release.

1 Like

I just learned about a SPEL expression which would allow using string queries :

@Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter}  AND #{[0]}")
Flux<String> findIdByDynamicN1ql(String queryStatement);

List<AIrport> l = airportRepository.findIdByDynamicN1ql("(name ='somename' OR state = 'CA')");

Technically, the whole statement could be #{[0]}, but I recommend using the provided n1ql.selectEntity and n1ql.filter as they are already constructed correctly for you.

Thank you @mreiche SPEL actually seems to be working, but is there a way i can see the exact n1ql query that Spring is using when i use SPEL.

Often I just put a syntax error in the query and then execute the query to generate an error - because the actual query string is included in the error message :slight_smile:

To use the logger - they are logged at ‘trace’ level by loggers under org.springframework.data.couchbase.core

This logback.xml will do it:

<?xml version="1.0" encoding="UTF-8"?>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
            <pattern>%d %5p %40.40c:%4L - %m%n</pattern>

    <root level="info">
        <appender-ref ref="console"/>
    <logger name="org.springframework.data.couchbase.core" level="trace"/>"
    <logger name="org.springframework.data.couchbase.repository.query" level="trace"/>

Oh got it!! Thank you for assisting me with my issues. SPEL expression has solved my issue