0

我有两节课,

@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
}

我的 JSON 文档是这样的,

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

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

    }
]
}

我应该如何编写查询方法以使用@Query注释通过 userId 和 questionID 查找 PracticeQuestion。

感谢您的任何建议。

4

1 回答 1

3

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

于 2014-12-10T07:36:58.540 回答