Search code examples
couchbasespring-data-couchbase

Return couchbase documents from keys


I want to retrieve all documents that exist based on list collection i have using spring-data-couchbase

Currently i am using

public interface PushRepository extends CrudRepository<Push,String> 

and function pushRepository.findAll(phoneNumbers) but i think it is retrieving all of them and then do the filtering .

How can i run a N1QL query so i only retrieve documents on keys

 @Query("#{#n1ql.selectEntity} WHERE role = 'admin' AND #{#n1ql.filter}")
 Collection<Push> findByIds(); 

The query i want to run is the below

select * from activation use keys ["xxxxx","yyyyy"];

Solution

  • The findAll(Iterable) uses an underlying view (which is supposed to index only the documents that correspond to your Push entity) but it does provide which view keys to restrict on, so it should already be pretty efficient.

    That said, if you want to do a N1QL query that directly uses document keys, that's still certainly possible with @Query. Since you use keys directly, there's no particular need for a WHERE clause (you know the keys correspond to Push documents). So you can simply do an inline query like this:

    @Query("#{#n1ql.selectEntity} USE KEYS [\"xxxxx\", \"yyyyy\"]")
    Collection<Push> myCustomFind();
    

    If you want to dynamically construct the list of keys, you'd have to look up the correct syntax but I bet this is doable using SpEL. For instance, taking two keys from the method parameters in the query signature can be done like this:

    @Query("#{#n1ql.selectEntity} USE KEYS [\"#{[0]}\", \"#{[1]}\"]")
    Collections<Push> findTwoByN1qlKey(String key1, String key2);