2015-09-25 109 views
0

我有以下文件文章聚集条款根据孩子集合属性

{ 
    title: "Some title", 
    authors: [ 
     { LastName: "Smith", Country: "US"}, 
     { LastName: "Smith", Country: "UK"}, 
    ] 
} 

我想添加一个条款聚合器基于作者的集合的性质国家的搜索。搜索应该返回所有不同国家的文章列表和聚合桶。看起来反向嵌套聚合是一条路,但我不能让它工作。

搜索聚合输出应该是这样的:

"aggregations": { 
    "countries": { 
     "buckets": [{ 
     "key": "US", 
     "doc_count": 1 
     }, { 
     "key": "UK", 
     "doc_count": 1 
     }] 
    } 
    } 
+0

你能现场的样本输出了。 –

回答

0

我认为你可以得到你想要有一个terms aggregation里面nested aggregation什么。

我成立了一个简单的指标是这样的:

PUT /test_index 
{ 
    "mappings": { 
     "doc": { 
     "properties": { 
      "authors": { 
       "type": "nested", 
       "properties": { 
        "Country": { 
        "type": "string", 
        "index": "not_analyzed" 
        }, 
        "LastName": { 
        "type": "string", 
        "index": "not_analyzed" 
        } 
       } 
      }, 
      "title": { 
       "type": "string" 
      } 
     } 
     } 
    } 
} 

然后增加了几个文件:

PUT /test_index/doc/1 
{ 
    "title": "Some title", 
    "authors": [ 
     { "LastName": "Smith", "Country": "US"}, 
     { "LastName": "Smith", "Country": "UK"} 
    ] 
} 

PUT /test_index/doc/2 
{ 
    "title": "another title", 
    "authors": [ 
     { "LastName": "Jones", "Country": "SA"}, 
     { "LastName": "Jones", "Country": "UK"} 
    ] 
} 

然后运行这个查询:

POST /test_index/_search?search_type=count 
{ 
    "aggs": { 
     "authors": { 
     "nested": { 
      "path": "authors" 
     }, 
     "aggs": { 
      "author_countries": { 
       "terms": { 
        "field": "authors.Country" 
       } 
      } 
     } 
     } 
    } 
} 

这似乎返回你想要什么:

{ 
    "took": 3, 
    "timed_out": false, 
    "_shards": { 
     "total": 1, 
     "successful": 1, 
     "failed": 0 
    }, 
    "hits": { 
     "total": 2, 
     "max_score": 0, 
     "hits": [] 
    }, 
    "aggregations": { 
     "authors": { 
     "doc_count": 4, 
     "author_countries": { 
      "doc_count_error_upper_bound": 0, 
      "sum_other_doc_count": 0, 
      "buckets": [ 
       { 
        "key": "UK", 
        "doc_count": 2 
       }, 
       { 
        "key": "SA", 
        "doc_count": 1 
       }, 
       { 
        "key": "US", 
        "doc_count": 1 
       } 
      ] 
     } 
     } 
    } 
} 

下面是一些代码我用来测试:

http://sense.qbox.io/gist/ccf7bd9d05f646507b3316e985dd6a50e905aed3

+0

嗨斯隆,这非常接近我正在寻找的!但有一个警告我无法修复。如果您有两个或两个以上作者在同一个国家/地区的文章,可以说英国,英国的存储区会返回一个与英国作者数相匹配的doc_count。我真正需要的是来自英国的文章数量。一种解决方案是在计数之前对国家总计应用独特的过滤器。我找不到办法做到这一点。 – Hernan