2017-02-10 265 views
0

elasticsearch 5.2Elasticsearch 5 |過濾器嵌套對象和嵌套聚合計數

我想通過嵌套對象state.id = 101篩選我的項目,並通過state.id篩選所有項目的聚合計數。有一些項目的狀態標識爲101,102和103.

聚合計數現在僅限於state.id 101.我只希望獲得帶有state.id = 101的項目和所有狀態ID的聚合計數。

我該怎麼做?

GET index/items/_search 
{ 
    "query": { 
     "nested" : { 
      "path" : "state", 
      "query": { 
       "bool": { 
       "filter": { 
        "term": { "state.id": 101 } 
       } 
       } 
      } 
     } 
    }, 
    "aggs" : { 
     "state" : { 
      "nested" : { 
       "path" : "state" 
      }, 
      "aggs" : { 
       "count" : { "terms" : { "field" : "state.id" } } 
      } 
     } 
    } 
} 

回答

1

您需要使用post_filter,而不是查詢:(發送有效載荷的時候哦,而不是使用GET,POST)

POST index/items/_search 
{ 
    "post_filter": {       <--- change this 
     "nested": { 
     "path": "state", 
     "query": { 
      "bool": { 
       "filter": { 
        "term": { 
        "state.id": 101 
        } 
       } 
      } 
     } 
     } 
    }, 
    "aggs": { 
     "state": { 
     "nested": { 
      "path": "state" 
     }, 
     "aggs": { 
      "count": { 
       "terms": { 
        "field": "state.id" 
       } 
      } 
     } 
     } 
    } 
} 

如果您想進一步縮小嵌套的聚集,也可以加一個過濾器:

POST index/items/_search 
{ 
    "post_filter": { 
     "nested": { 
     "path": "state", 
     "query": { 
      "bool": { 
       "filter": { 
        "term": { 
        "state.id": 101 
        } 
       } 
      } 
     } 
     } 
    }, 
    "aggs": { 
     "narrow": { 
     "filter": { 
      "nested": { 
       "path": "state", 
       "query": { 
        "bool": { 
        "filter": { 
         "term": { 
          "state.id": 101 
         } 
        } 
        } 
       } 
      } 
     }, 
     "aggs": { 
      "state": { 
       "nested": { 
        "path": "state" 
       }, 
       "aggs": { 
        "count": { 
        "terms": { 
         "field": "state.id" 
        } 
        } 
       } 
      } 
     } 
     } 
    } 
} 
+0

謝謝。正是我需要的。還有一個問題。我想將當前的聚合上下文縮小到一組特定的文檔。我如何在嵌套聚合中使用過濾器聚合。 [鏈接](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html) – Joost

+1

酷,很高興它幫助。我已經更新了我的答案。 – Val

+0

Thx。但是,我想過濾嵌套對象上的聚合。 ''' 「過濾器」:{ 「術語」:{ 「state.id」:[101,102] }} , ''' 而只能從 「state.id」 文件:101像上面一樣。 – Joost