Spring Data elasticsearch @Query注释用于嵌套对象 [英] Spring Data elasticsearch @Query annotation for nested objects

查看:2672
本文介绍了Spring Data elasticsearch @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文档就是这样,

My JSON doc is like this,

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

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

    }
]
}

如何使用 @Query 注释

感谢任何建议。

推荐答案

如果要通过userId和QuestionId进行搜索。您有2个选项。

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


  1. 使用嵌套查询(上述示例中的问题是嵌套对象和弹性搜索支持搜索嵌套对象。 )。您可以阅读更多关于它的信息 here

  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.

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

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. 如果不想使用嵌套对象,请将规范化模式并将问题和userId平铺在同一级别,然后对userId和QuestionId发出查询

例如
文件1

e.g. Document 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);
}

请参阅此链接了解更多示例

这篇关于Spring Data elasticsearch @Query注释用于嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆