Elasticsearch DSL python在嵌套属性上查询过滤器和聚合

时间:2017-01-09 22:44:12

标签: python elasticsearch elasticsearch-dsl

我想使用嵌套对象进行过滤来构建过滤的Elasticsearch查询,并进行聚合以获取嵌套对象列表中嵌套对象的最小值。

过滤部分有效,但我无法将其与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字段)

1 个答案:

答案 0 :(得分:3)

添加

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

应该可以解决问题。

相关问题