ElasticSearch在不影响“父”对象的情况下过滤嵌套对象

2024-09-29 22:01:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个blog对象的ElasticSearch映射,其中包含一个嵌套的评论字段。这样用户就可以向上面显示的博客内容添加评论。comments字段有一个published标志,该标志决定评论是否可以由其他用户查看,还是仅由主用户查看。在

"blogs" :[
{
     "id":1,
     "content":"This is my super cool blog post",
     "createTime":"2017-05-31",
      "comments" : [
            {"published":false, "comment":"You can see this!!","time":"2017-07-11"}
       ]
},
{
     "id":2,
     "content":"Hey Guys!",
     "createTime":"2013-05-30",
     "comments" : [
               {"published":true, "comment":"I like this post!","time":"2016-07-01"},
               {"published":false, "comment":"You should not be able to see this","time":"2017-10-31"}
       ]
},
{
     "id":3,
     "content":"This is a blog without any comments! You can still see me.",
     "createTime":"2017-12-21",
     "comments" : None
},
]

我想能够过滤评论,以便只有真正的评论将显示每个博客对象。我想展示每一个博客,而不仅仅是那些有真实评论的博客。我在网上找到的所有其他解决方案似乎都会影响我的博客对象。在没有评论的情况下查询blogs是否会影响到所有的评论?在

因此,上面的示例将在查询后返回:

^{pr2}$

这个例子仍然显示了没有评论或错误评论的博客。在

这可能吗?在

我一直在使用这个示例中的嵌套查询:ElasticSearch - Get only matching nested objects with All Top level fields in search response

但是这个例子会影响博客本身,并且不会返回只有错误评论或者没有评论的博客。在

请帮忙:)谢谢!在


Tags: 对象用户youidtimecomment评论blog
1条回答
网友
1楼 · 发布于 2024-09-29 22:01:19

好的,所以我发现使用elasticsearch查询显然没有办法做到这一点。但我找到了一种在django/python端实现这一点的方法(这正是我需要的)。我不确定是否有人需要这些信息,但是如果您需要这些信息并且使用Django/ES/REST,这就是我所做的。在

我按照elasticsearch dsl文档(http://elasticsearch-dsl.readthedocs.io/en/latest/)将elasticsearch与我的Django应用程序连接起来。然后我使用rest_framework_elasticsearch包框架来创建视图。在

要创建只查询elasticsearch项列表中True嵌套属性的Mixin,请创建rest\u框架的Mixin子类_elastic.es_混音器ListLastICMixin对象。然后在我们的新mixin中重写esu表示定义,如下所示。在

class MyListElasticMixin(ListElasticMixin):
    @staticmethod
    def es_representation(iterable):

        items = ListElasticMixin.es_representation(iterable)

        for item in items:
            for key in item:
                if key == 'comments' and item[key] is not None:
                    for comment in reversed(item[key]):
                        if not comment['published']:
                            item[key].remove(comment)

        return items

请确保在注释的for循环中使用reversed函数,否则将跳过列表中的一些注释。在

我用这个新的过滤器。在

^{pr2}$

在python端做这件事肯定更容易,也更有效。在

相关问题 更多 >

    热门问题