每个文档的 Python elasticsearch DSL 聚合/嵌套值度量

标签 python elasticsearch elasticsearch-dsl

我试图在 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 字段)

最佳答案

如果您想要每个文档的最小值,则将所有 嵌套 存储桶放入一个存储桶 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 或在应用程序中计算每个文档的最小值可能更容易。

关于每个文档的 Python elasticsearch DSL 聚合/嵌套值度量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594609/

相关文章:

ruby-on-rails - Elasticsearch排序选项不受支持

python - Elasticsearch dsl删除错误

django - 通过地理空间数据排序并基于字段向上移动特定记录-ElasticSearch DSL DRF

elasticsearch - 嵌套查询是否用于ElasticSearch中的对象映射?

python - 属性错误: 'Response' object has no attribute 'json'

Python将8个对象循环组合成3组,3-3-2

python - 为已安装的字体创建标签名称并以字体样式显示字体名称

python - 计算两个字符串python之间的匹配次数

elasticsearch - ElasticSearch查询字段不起作用

spring-boot - Elasticsearch 分析器在通过 Spring Data 创建时工作,但在直接从 Postman/curl 创建时失败