Search code examples
javacouchbasesql++spring-data-couchbase

Using IN clause in couchbase N1Ql @query or use findAll(keys) from couchbase JPA


I am using Spring couchbase JPA and trying to fetch documents by giving a list of keys. My repository structure looks something like

    public interface EmployeeRepo
    extends CouchbasePagingAndSortingRepository<Employee, String>, EmployeeCustomRepo {   

I have a list of employee ids to search for and fetch the corresponding document. I tried using the method from curdRepository

    public List<Employee> findAllById(List<String> empIds) {
        return employeeRepo.findAll(empIds);
    }

But I get exception as::

org.springframework.dao.InvalidDataAccessResourceUsageException: 
View employee/all does not exist.; nested exception is 
com.couchbase.client.java.error.ViewDoesNotExistException: View 
employee/all does not exist.

Even I tried wrapping my list of keys to an Iterable object as well. But the exception remains the same.

    public List<Employee> findAllById(List<String> empIds) {
        Iterable<String> itrKeys = empIds;
        return employeeRepo.findAll(itrKeys);
    }

Furthermore, I tried using N1QL with @query over method

      @Query("#{#n1ql.selectEntity} WHERE meta().id IN $ids AND #{#n1ql.filter}")
Collection<ProductCopy> findAllById(@Param("ids") JsonArray ids);

I converted my list of keys to JsonArray. and above findAllById() method doesn't throw any exception, but gives no document even when I have matching keys.

      @Query("#{#n1ql.selectEntity} USE KEYS ($ids) ")
Collection<ProductCopy> findByIdIn(@Param("ids") JsonArray ids);

And on executing findByIdIn() I get this exception n1ql errors: {"msg":"Missing or invalid primary key.

My question is why findAll(Iterable id)/findAll(List id) is not working,when findOne(String id) works smooth and how do I create a parameterized N1QL query which can take multiple items in an IN statement?

Solution

  • Try adding both @N1qlPrimaryIndexed and @ViewIndexed annotations, like in the following example:

    @N1qlPrimaryIndexed
    @ViewIndexed(designDoc = "businessUnity")
    public interface BusinessUnityRepository extends CouchbaseRepository<BusinessUnity, String>{
    
    List<BusinessUnity> findByCompanyId(String companyId);
    
    }
    

    Additionally, you can also check this tutorial:

    https://blog.couchbase.com/couchbase-spring-boot-spring-data/