【问题标题】:How to build a search query with filtering for nested objects in spring-data elastic search?如何在spring-data弹性搜索中通过过滤嵌套对象来构建搜索查询?
【发布时间】:2020-11-03 23:36:30
【问题描述】:

我的文档是这样的:

class Foo{
 private Integer idDl;
 private String Name;
 private String Add;
 @Field(type = FieldType.Nested)
 private List< Bar> Bar;
 }
 
 class Bar{
 private Integer barId;
 private List<String> barData
 }

Foo的样本数据是这样的:

{
    "idDl": 123,
    "Name": "ABCD",
    "Add": "FL",
    "Bar": [
        {
            "barId": 456,
            "barData": [
                "Bar1",
                "Bar2"
            ]
        },
        {
            "barId": 985,
            "barData": [
                "Bar4",
                "Bar5"
            ]
        }
    ]
}

我想返回所有Bar.barId 匹配的Fooobjects,但由于BarFoo 中的列表对象,Foo 必须只包含一个Bar 对象,其ID 与ID 匹配由用户提供。我使用 spring-data-elasticsearch 提供的NativeSearchQueryBuilder 为:

String[] includeFields = new String[]{"idDl", "Name"};
String[] excludeFields = new String[]{"Add"}; // to exclude Add field of Foo
Query searchQuery = new NativeSearchQueryBuilder()
            .withQuery(matchQuery("Bar.barId", 456))
            //.withQuery(termQuery("Bar.barId", 456))
            .withSourceFilter(new FetchSourceFilter(includeFields, excludeFields))
            .build();
return elasticsearchRestTemplate.queryForList( searchQuery, Foo.class);

我得到的响应包括所有 Bar 对象,与 ID 无关,这里是示例响应:

[
    {
        "idDl": 123,
        "Name": "ABCD",
        "Add": "FL",
        "Bar": [
            {
                "barId": 456,
                "barData": [
                    "Bar1",
                    "Bar2"
                ]
            },
            {
                "barId": 985,
                "barData": [
                    "Bar4",
                    "Bar5"
                ]
            }
        ]
    },
    {
        "idDl": 758,
        "Name": "PQR",
        "Add": "NY",
        "Bar": [
            {
                "barId": 456,
                "barData": [
                    "Bar1",
                    "Bar2"
                ]
            },
            {
                "barId": 671,
                "barData": [
                    "Bar24",
                    "Bar25"
                ]
            }
        ]
    }
]

我尝试使用在 sn-p 中评论的termQuery,但我没有得到响应,而对于matchQuery,我得到了上述响应。在响应中,Bar 必须仅包含 ID 为 456 的对象,即在查询中发送的 ID。任何建议都会有所帮助

【问题讨论】:

    标签: spring-boot spring-mvc elasticsearch spring-data spring-data-elasticsearch


    【解决方案1】:

    您正在查询Foo 对象,其中存在与条件匹配的Bar,Elasticsearch 会返回这些Foos。如果您想要唯一匹配的 Bars,您需要将 inner_hits 添加到您的查询中。

    检查this question 并回答如何检索这些,使用 Spring Data Elasticsearch 检索内部命中将随版本 4.1 提供。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 2015-05-27
      相关资源
      最近更新 更多