2017-08-03 173 views
0

我有一個工作的elasticsearch查詢,但我無法弄清楚如何使用java API解析返回值。看起來無論我怎樣配置它,我都會遇到空值。Elasticsearch中的聚合解析

查詢在elastisearch是:

GET user_profile/active_time/_search 
{ 
    "size" : 0, 
    "aggregations" : { 
    "agg1" : { 
     "filter" : { 
     "range" : { 
      "timestamp" : { 
      "from" : 0, 
      "to" : 1501786179177, 
      "include_lower" : true, 
      "include_upper" : true 
      } 
     } 
     }, 
     "aggregations" : { 
     "agg2" : { 
      "terms" : { 
      "field" : "userId", 
      "size" : 0 
      } 
     } 
     } 
    } 
    } 
} 

它產生的返回值:

{ 
    "took": 2, 
    "timed_out": false, 
    "_shards": { 
    "total": 5, 
    "successful": 5, 
    "failed": 0 
    }, 
    "hits": { 
    "total": 55, 
    "max_score": 0, 
    "hits": [] 
    }, 
    "aggregations": { 
    "agg1": { 
     "doc_count": 55, 
     "agg2": { 
     "doc_count_error_upper_bound": 0, 
     "sum_other_doc_count": 0, 
     "buckets": [ 
      { 
      "key": 0, 
      "doc_count": 34 
      }, 
      { 
      "key": 295, 
      "doc_count": 12 
      }, 
      { 
      "key": 59, 
      "doc_count": 3 
      }, 
      { 
      "key": 764, 
      "doc_count": 3 
      }, 
      { 
      "key": 788, 
      "doc_count": 3 
      } 
     ] 
     } 
    } 
    } 
} 

我不知道如何正確地得到桶出來聚集2.在以前的迭代中,我能夠使用來訪問它

Terms terms = sr.getProperty("agg2");

但過濾器在那種情況下不起作用。我應該重新格式化我的查詢還是有一些方法來解析這個?謝謝。

回答

0

通過將範圍過濾器移出聚合並轉換爲正常搜索,我能夠使用這些行解析值。

Terms terms = sr.getAggregations().get("agg"); 
Collection<Terms.Bucket> buckets = terms.getBuckets(); 
for (Terms.Bucket x : buckets) { 
     System.out.println("Key: " + x.getKey() + " Count: " + x.getDocCount()); 
} 

這裏的新查詢:

GET user_profile/active_time/_search 
{ 
    "size" : 0, 
    "query": { 
    "range": { 
     "timestamp": { 
     "gte": 0, 
     "lte": 1501786179177 
     } 
    } 
    }, 
    "aggregations" : { 
    "agg1" : { 
      "terms" : { 
      "field" : "userId", 
      "size" : 0 
      } 
     } 
    } 
}