【问题标题】:Nested objects and aggregations嵌套对象和聚合
【发布时间】:2015-09-10 22:09:49
【问题描述】:

我有这个映射到我的 ES 数据库中,它使用了嵌套对象。

每个文档都是一个公司,并有一个保存为嵌套对象的员工列表。 这是映射:

 "company": {
    "properties": {
        "company_name": {
           "type": "string"
        },

       "employee": {
          "properties": {
              "name": {
                 "type": "string"
               },
              "city": {
                 "type": "string"
              }
          },
          "type": "nested"
        }
      }
    }
  }
}

我有这两家公司:

Company A 
    [
    Smith, Dallas
    Mark, New York
    Smith, Houston
    ]

Company B 
    [
    Smith, Dallas
    Peter, New York
    Mary, Houston
    ]

也就是说,同一个名字可以在不同的公司中找到,并且在每个公司中不止一次。

我需要运行的查询应该是这个:

汇总所有姓名为 Smith 的员工所在的城市

我需要这样的答案:

City for employee Smith:
   Dallas:  2
   Houston: 1

记住员工是嵌套对象的列表,我不需要有关公司名称的任何信息。

【问题讨论】:

    标签: elasticsearch nested


    【解决方案1】:

    试试这个

    {
       "size": 0,
       "aggs": {
          "my_aggs": {
             "nested": {
                "path": "employee"
             },
             "aggs": {
                "city_for_smith": {
                   "filter": {
                      "term": {
                         "name": "smith"
                      }
                   },
                   "aggs": {
                      "result": {
                         "terms": {
                             "field": "city"
                         }
                      }
                   }
                }
             }
          }
       }
    }
    

    要同时显示每个城市的公司名称,您可以在最后一个聚合中嵌套另一个聚合。

    {
      ...
      "aggs": {
        "result": {
          "terms": {
            "field": "city"
          },
          "aggs": {
            "companyAggs": {
              "reverse_nested": {}, 
              "aggs": {
                "in_company": {
                  "terms": {
                    "field": "company_name"
                  }
                }
              }
            }
          }
        }
      }
    }

    【讨论】:

    • 谢谢瑞恩!它有效:) 是否可以在同一个查询中显示在同一个查询中匹配的公司名称?员工史密斯所在的城市:达拉斯:2 家 A 公司,B 休斯顿:1 家 A 公司
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2021-08-09
    相关资源
    最近更新 更多