2017-09-14 253 views
1

對於包含註釋的嵌套字段的博客對象,我有一個ElasticSearch映射。這樣用戶就可以向上面顯示的博客內容添加評論。註釋字段具有已發佈的標誌,用於確定註釋是否可以被其他用戶查看,或者僅由主要用戶查看。ElasticSearch - 在不影響「父」對象的情況下過濾嵌套對象

"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 - Get only matching nested objects with All Top level fields in search response

但是這個例子影響了自己的博客,並不會返回只有虛假評論或沒有評論的博客。

請幫忙:)謝謝!

回答

0

好吧,所以發現顯然沒有辦法使用elasticsearch查詢來做到這一點。但我想出了一個在django/python端執行此操作的方法(這正是我所需要的)。我不確定是否有人會需要這些信息,但如果您需要這些信息,並且您正在使用Django/ES/REST,那我就是這麼做的。

我遵循elasticsearch-dsl文檔(http://elasticsearch-dsl.readthedocs.io/en/latest/)將elasticsearch與我的Django應用程序連接起來。然後,我使用rest_framework_elasticsearch軟件包框架來創建視圖。

要創建僅在彈性搜索項列表中查詢嵌套屬性True的Mixin,請創建rest_framework_elastic.es_mixins ListElasticMixin對象的mixin子類。然後在我們新的mixin中覆蓋es_representation定義如下。

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 

確保您使用reversed功能中的評論循環,否則你會跳過一些在列表中您的意見。

這個我在我看來使用這個新的過濾器。

class MyViewSet(MyListElasticMixin, viewsets.ViewSet): 
    # Your view code here 

    def get(self, request, *args, **kwargs): 
     return self.list(request, *args, **kwargs) 

在python方面做它肯定更容易和工作。

相關問題