2

我正在尝试在 2 级嵌套中找到最小值(最小值)(每个文档的单独最小值)。

到目前为止,我能够进行聚合,从我的搜索结果中的所有嵌套值中计算最小值,但每个文档没有分离。

我的示例架构:

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
        }
    )
)

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

基本上我需要做的是获取每个唯一 MyExample 的所有嵌套 nested1.foo.bar 值的最小值(它们具有唯一的 myexample_id 字段)

4

1 回答 1

2

如果您想要每个文档的最小值,则将所有nested存储桶放在存储桶terms聚合中的myexample_id字段上:

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

请注意,这种聚合计算起来可能非常昂贵,因为它必须为每个文档创建一个存储桶。对于这样的用例,可能更容易在每个文档的基础上计算最小值作为script_field应用程序或应用程序。

于 2017-01-12T09:05:33.443 回答