【问题标题】:ElasticSearch count nested fieldsElasticSearch 计数嵌套字段
【发布时间】:2019-07-21 21:45:37
【问题描述】:

在 ElasticSearch 中,如何计算满足特定条件的嵌套字段(即嵌套对象列表)的对象?

示例

拥有客户索引,类型为客户,其服务嵌套字段具有以下结构:

public class Customer
{
    public int Id;
    public List<Service> Services;
}

public class Service
{
    public int Id;
    public DateTime Date;
    public decimal Rating;
}

如何计算 2017 年 6 月发生且评分高于 5 的所有服务?

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    好问题:) 为了得到你想要的,你应该预先定义你的映射并且嵌套的属性映射效果很好。

    嵌套类型是对象数据类型的特殊版本,它允许对象数组相互相互独立进行索引和查询。 https://www.elastic.co/guide/en/elasticsearch/reference/2.4/nested.html

    请在下面找到完整示例:)

    映射

    PUT example_nested_test
    {
      "mappings": {
        "nested": {
          "properties": {
            "Id": {
              "type": "long"
            },
            "Services": {
              "type": "nested",
              "properties": {
                "Id": {
                  "type": "long"
                },
                "Date": {
                  "type": "date"
                },
                "Rating": {
                  "type": "long"
                }
              }
            }
          }
        }
      }
    }
    

    发布数据

    POST example_nested_test/nested/100
        {
          "Id" : 1,
          "Services": [
            {
              "Id": 1,
              "Date" :"2017-05-10",
              "Rating" : 5
            },
             {
              "Id": 2,
              "Date" :"2013-05-10",
              "Rating" : 2
            },
            {
              "Id": 4,
              "Date" :"2017-05-10",
              "Rating" : 6
            }]
        }
    

    查询

    GET example_nested_test/_search
    {
      "size":0, 
      "aggs": {
        "Services": {
          "nested": {
            "path": "Services"
          },
          "aggs": {
            "Rating": {
              "filter": {
                "bool": {
                  "must": [
                    {
                      "range": {
                        "Services.Date": {
                          "gt": "2017",
                          "format": "yyyy"
                        }
                      }
                    },
                    {
                      "range": {
                        "Services.Rating": {
                          "gt": "5"
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      }
    }
    

    结果

     "aggregations": {
        "Services": {
          "doc_count": 3,
          "Rating": {
            "doc_count": 1
          }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2020-04-16
      相关资源
      最近更新 更多