问题
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:
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
来源:https://stackoverflow.com/questions/27374618/spring-data-elasticsearch-query-annotation-for-nested-objects