Spring Data 弹性搜索@Query嵌套对象的注释



我有两个类,

@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注释按用户 ID 和问题 ID 查找实践问题。

感谢您的任何建议。

如果要按用户ID和问题ID进行搜索。您有 2 个选项。

  1. 使用嵌套查询(上面示例中的问题是一种嵌套对象,elasticsearch 支持对嵌套对象进行搜索(。您可以在此处阅读有关它的更多信息。

您可以使用方法创建PracticeQuestionRepository findByUserId,如下所示。

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. 如果不想使用嵌套对象。De 规范化架构并在同一级别平展问题和用户 ID,然后对用户 ID 和问题 ID 发出查询。

例如文档 1

{
    "_id": "506d9c0ce4b005cb478c2e97",
    "userId": 1,
    "questionID": 1,
    "type": "optional"
}

文档 2

{
    "_id": "506d9c0ce4b005cb478c2e97",
    "userId": 1,
    "questionID": 1,
    "type": "optional"
}

存储库代码

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

有关更多示例,请参阅此链接

最新更新