0

I have two class,

@Document
public class PracticeQuestion {

     private int userId;
     private List<Question> questions;

// Getters and setters
}


public class Question {

     private int questionID;
     private String type;

// Getters and setters
}

My JSON doc is like this,

{
"_id" : ObjectId("506d9c0ce4b005cb478c2e97"),
"userId" : 1,
"questions" : [
    {
        "questionID" : 1,
        "type" : "optional"

    },
    {
        "questionID" : 3,
        "type" : "mandatory"

    }
]
}

How should I write the query method to find PracticeQuestion by userId and questionID using @Query annotation.

Thanks for any suggestion.

1 Answer 1

4

If you want to search by userId and QuestionId. You have 2 options.

  1. 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);
}
  1. 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

Sign up to request clarification or add additional context in comments.

3 Comments

sorry, I have updated my question as "method to find PracticeQuestion by userId and questionID using @Query annotation".
I updated my answer based on the userId and questionId query.
Guys, sorry for using this question but it's very similar, how to do a query by Date field less than the date parameter? Optional<List<Evento>> findByDataLessThan(LocalDateTime data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.