代码之家  ›  专栏  ›  技术社区  ›  chowpay

python弹性搜索dsl返回特定密钥的所有唯一值

  •  0
  • chowpay  · 技术社区  · 3 年前

    我有一个名为的字段 account_number 。它包含随机的6个字符串。

    我似乎无法让python elasticsearch dsl只返回那些唯一的值。

    search = Search(using=client, index=index_name).query(
             {
              "range": {
                "date": {
                  "gte": "2021-08-01T08:00:00.000Z",
                  "lte": "2021-08-31T23:59:59.599Z"
                  #"format": "strict_date_optional_time"
                }
            }
        })
    
     
    search.aggs.bucket("account_number","terms",field="account_number",size="1000")
    
    es_data = search.execute()
    

    不确定我是否需要在查询中定义account_number,或者它是否在agg桶中?。现在,我只得到随机返回的完整行和所有列

    这里是一个非dsl形式的工作查询的例子。我认为度量不是必需的,但也许是必需的。

    {
      "aggs": {
        "3": {
          "terms": {
            "field": "account_number",
            "order": {
              "1": "desc"
            },
            "size": 5
          },
          "aggs": {
            "1": {
              "sum": {
                "field": "hits"
              }
            }
          }
        }
      },
      "size": 0,
      "stored_fields": [
        "*"
      ],
      "script_fields": {},
      "docvalue_fields": [
        {
          "field": "@timestamp",
          "format": "date_time"
        },
        {
          "field": "date",
          "format": "date_time"
        }
      ],
      "_source": {
        "excludes": []
      },
      "query": {
        "bool": {
          "must": [],
          "filter": [
            {
              "match_all": {}
            },
            {
              "range": {
                "date": {
                  "gte": "2021-04-08T21:00:00.000Z",
                  "lte": "2021-10-08T21:00:00.000Z",
                  "format": "strict_date_optional_time"
                }
              }
            }
          ]
        }
      }
    }
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   akdev    2 年前

    您可以添加 extra(size=0) 对您的查询:

    search = Search(using=client, index=index_name).query(
             {
              "range": {
                "date": {
                  "gte": "2021-08-01T08:00:00.000Z",
                  "lte": "2021-08-31T23:59:59.599Z"
                  #"format": "strict_date_optional_time"
                }
            }
        }).extra(size=0)
    

    然后你的 es_data 将为空,并且 es_data.aggregations.account_number.buckets 将只包含唯一的帐号。

    希望能有所帮助。