Python弹性搜索DSL聚合/每个文档的嵌套值的度量 [英] Python elasticsearch DSL aggregation/metric of nested values per document

查看:259
本文介绍了Python弹性搜索DSL聚合/每个文档的嵌套值的度量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find the minimum (smallest) value in a 2-level nesting (separate minimum value per document).

到目前为止,我可以要进行聚合,从我的搜索结果中的所有嵌套值计算最小值,但不包含每个文档。

So far I'm able to make an aggregation which counts the min value from all the nested values in my search results but without separation per document.

我的示例模式:

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

m搜索和聚合:

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

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

Basically what I need to do is to get the min value for all the nested nested1.foo.bar values for each unique MyExample (they have unique myexample_id field)

推荐答案

如果你想要每个文档的最小值,那么把所有的嵌套桶中的桶条款聚合超过 myexample_id 字段:

If you want minimum value per document then put all the nested buckets within a bucket terms aggregation over myexample_id field:

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 或应用程序的形式计算最小值。

Note that this aggregation might be extremely expensive to calculate since it has to create a bucket for each document. For a use case like this it might be easier to compute the minimum on a per document basis as a script_field or in the app.

这篇关于Python弹性搜索DSL聚合/每个文档的嵌套值的度量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆