ElasticSearch - 过滤嵌套对象而不影响"parent"对象



我为博客对象提供了一个包含嵌套字段的博客映射。因此,用户可以将注释添加到上面显示的博客内容中。评论字段具有已发布的标志,该标志决定了其他用户还是仅由主要用户查看该评论。

"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" :[
{
     "id":1,
     "content":"This is my super cool blog post",
     "createTime":"2017-05-31",
      "comments" : None # OR EMPTY LIST 
},
{
     "id":2,
     "content":"Hey Guys!",
     "createTime":"2013-05-30",
     "comments" : [
               {"published":true, "comment":"I like this post!","time":"2016-07-01"}
       ]
},
{
     "id":3,
     "content":"This is a blog without any comments! You can still see me.",
     "createTime":"2017-12-21",
     "comments" : None
},
]

该示例仍然显示没有注释或错误评论的博客。

这可能吗?

我一直在使用此示例中的嵌套查询:elasticsearch-仅获取与搜索响应中所有顶级字段的匹配对象

中的所有顶级字段

但是,此示例会影响博客本身,并且不会返回只有虚假评论或没有评论的博客。

请帮助:)谢谢!

好的,因此发现使用Elasticsearch查询显然无法执行此操作。但是我想出了一种在django/python方面执行此操作的方法(这是我需要的)。我不确定是否有人需要此信息,但是如果您需要此信息,并且您正在使用django/es/休息,这就是我所做的。

我遵循Elasticsearch-DSL文档(http://elasticsearch-dsl.readthedocs.io/en/latest/),将Elasticsearch与我的Django应用联系起来。然后,我使用REST_FRAMEWORK_ELASTICSERACH软件包框架来创建视图。

创建一个仅查询Elasticsearch项目列表中True嵌套属性的混合蛋白,请创建REST_FRAMEWORK_ELASTIC.ES_MIXINS listelasticmixin对象的Mixin子类。然后覆盖es_ crementation定义,如下所示。

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函数,否则您将跳过列表中的某些评论。

我在视图中使用了这个新过滤器。

class MyViewSet(MyListElasticMixin, viewsets.ViewSet):
   # Your view code here
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

在python方面做到这一点绝对更容易且有效。

最新更新