2017-01-09 102 views
4

我想使用通過嵌套對象進行過濾來構建過濾的Elasticsearch查詢,並進行聚合以獲取嵌套對象列表中嵌套對象的最小值。Elasticsearch在嵌套屬性上使用過濾器和聚合的DSL python查詢

過濾部分工作,但我不能將它與aggs(聚合)部分綁定。 當我在過濾器之後將.aggs.bucket部件添加到我的代碼中時,它會被忽略(在search.to_dict()中不可見)或者給我語法錯誤。

任何人都可以給我一個關於如何將它們綁定在一起的例子嗎?我試圖讓這兩個過濾查詢結果結束一個響應

示例模式從nested1.foo.bar計算的最小值:

class MyExample(DocType): 
    myexample_id = Integer() 
    nested1 = Nested(
     properties={ 
      'timestamp': Date(), 
      'foo': Nested(
       properties={ 
        'bar': Float(), 
       } 
      ) 
     } 
    ) 
    nested2 = Nested(
     multi=False, 
     properties={ 
      'x': String(), 
      'y': String(), 
     } 
    ) 

構建查詢:

from elasticsearch_dsl import Search, Q 

search = Search().filter(
    'nested', path='nested1', inner_hits={}, 
    query=Q(
     'range', **{ 
      'nested1.timestamp': { 
       'gte': exampleDate1, 
       'lte': exampleDate2 
      } 
     } 
    ) 
).filter(
    'nested', path='nested2', inner_hits={'name': 'x'}, 
    query=Q(
     'term', **{ 
      'nested2.x': x 
     } 
    ) 
).filter(
    'nested', path='nested2', inner_hits={'name': 'y'}, 
    query=Q(
     'term', **{ 
      'nested2.y': y 
     } 
    ) 
) 

基本上我需要什麼要做的是獲取每個唯一MyExample文檔的所有嵌套nested1.foo.bar值的最小值(它們具有唯一的myexample_id字段)

回答

3

添加

search.aggs\ 
    .bucket('nested1', 'nested', path='nested1')\ 
    .bucket('nested_foo', 'nested', path='nested1.foo')\ 
    .metric('min_bar', 'min', field='nested1.foo.bar') 

下一行應該做的伎倆。

+0

是否有可能分別在''''''''nested1'''中爲每組'''foo.bar''獲取最小值?更改:將所有'''foo'''中的所有'''bar'聚合在一個嵌套1中並獲得最小值? – user2091046

+0

我已經編輯了一下'''MyExample'''。 基本上我需要做的是獲得每個唯一'''MyExample'''的所有嵌套'nested1.foo.bar''值的最小值(它們具有唯一'''myexample_id'''字段) – user2091046

+1

在這裏看到我的答案:http://stackoverflow.com/questions/41594609/python-elasticsearch-dsl-aggregation-metric-of-nested-values-per-document/41608959#41608959 –