If you want to search by userId and QuestionId. You have 2 options.
- Use nested queries (Questions in the example above is kind of a nested object and elasticsearch support search on nested objects.). You can read more about it here.
You can create PracticeQuestionRepository
with a method findByUserId like shown below.
public interface PracticeQuestionRepository extends ElasticsearchRepository<PracticeQuestion, String> {
@Query("{"query":{"bool":{"must":[{"match":{"userId":"?0"}},{"nested":{"path":"questions","query":{"bool":{"must":[{"match":{"questions.id":"?1"}}]}}}}]}}}")"
Page<PracticeQuestion> findByUserIdAndQuestionId(String userId, String questionId, Pageable pageable);
}
- If you do not want to use nested objects. De normalize the schema and flatten the question and userId at the same level and then issue a query on userId and QuestionId.
e.g.
Document 1
{
"_id": "506d9c0ce4b005cb478c2e97",
"userId": 1,
"questionID": 1,
"type": "optional"
}
Document 2
{
"_id": "506d9c0ce4b005cb478c2e97",
"userId": 1,
"questionID": 1,
"type": "optional"
}
Code for Repository
public interface PracticeQuestionRepository extends ElasticsearchRepository<PracticeQuestion, String> {
@Query("{"bool" : {"must" : [ {"field" : {"userId" : "?0"}}, {"field" : {"questionId" : "?1"}} ]}}"")
Page<PracticeQuestion> findByUserIdAndQuestionId(String userId, String questionId, Pageable pageable);
}
Refer this link for more examples