How to search by field in embeded list of objects using Spring repository for Couchbase

Viewed 37

I have following User Document:

@Document
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationStrategy.UNIQUE)
    private String id;

    @Field
    private String email;

    @Field
    private String fullName;

    @Field
    private LocalDate birthDate;

    @Field
    private Gender gender;

    @Field
    private List<Sport> sports = new ArrayList<>();
}

and Sport class:

@Data
public class Sport {

    private String id;

    private String sportName;

    private SportProficiency sportProficiency;

}

How can I create a method in UserRepository, to search for users by sport name? I have tried

@Query("#{#n1ql.selectEntity} unnest Users.sports s where s.sportName = $1")
List<User> findAllUsersBySportName(String sportName);

which gives me com.couchbase.client.core.error.ParsingFailureException: Parsing of the input failed

And

List<User> findAllBySports_SportName(String sportName);

which just builds an incorrect query and returns an empty list.

2 Answers

I came up with the following query:

@Query("#{#n1ql.selectEntity} where any s in Users.sports satisfies s.sportName in [$1] end;")
List<User> findAllUsersBySportName(String sportName);

This is not the best solution, but at least it's working. If you have a better solution, please post an answer.

Related