2017-06-14 90 views
0

我是Elasticsearch的新手,無法弄清楚如何解決以下問題。 解釋我的問題的最簡單方法是向您展示一個示例。Elasticsearch只聚集在一個數組中的特定條目

以下數組「列表」是Elasticsearch中所有文件的一部分,但條目有所不同,因此具有「id」42的「person」可能位於我的文件的50%中。我想要做的是在Elasticsearch的所有文件中獲得ID爲42的所有人的平均「排名。位置標準」。

{ 
"listing": [ 
    { 
     "person": { 
      "id": 42 
     }, 
     "ranking": { 
      "position": { 
       "standard": 2 
      } 
     } 
    }, 
    { 
     "person": { 
      "id": 55 
     }, 
     "ranking": { 
      "position": { 
       "standard": 7 
      } 
     } 
    } 
] 
} 

感謝您的幫助!

+0

你到目前爲止嘗試過什麼? –

+0

我嘗試了各種過濾。到目前爲止,我所取得的所有成果都是爲了讓整個文件恢復正常,如果「列表」數組中有一個「id」爲42的條目。 – McClane

回答

0

首先,您是否將商品存儲爲objectnested數據類型?我不認爲它會工作,如果它是一個object,所以嘗試下面的例子:

PUT /test 
{ 
    "mappings": { 
    "_default_": { 
     "properties": { 
     "listing": { 
      "type": "nested" 
     } 
     } 
    } 
    } 
} 

PUT /test/aa/1 
{ 
    "listing": [ 
    { 
     "person": { 
     "id": 42 
     }, 
     "ranking": { 
     "position": { 
      "standard": 2 
     } 
     } 
    }, 
    { 
     "person": { 
     "id": 55 
     }, 
     "ranking": { 
     "position": { 
      "standard": 7 
     } 
     } 
    } 
    ] 
} 

PUT /test/aa/2 
{ 
    "listing": [ 
    { 
     "person": { 
     "id": 42 
     }, 
     "ranking": { 
     "position": { 
      "standard": 5 
     } 
     } 
    }, 
    { 
     "person": { 
     "id": 55 
     }, 
     "ranking": { 
     "position": { 
      "standard": 6 
     } 
     } 
    } 
    ] 
} 

GET test/_search 
{ 
    "size": 0, 
    "aggs": { 
    "nest": { 
     "nested": { 
     "path": "listing" 
     }, 
     "aggs": { 
     "persons": { 
      "terms": { 
      "field": "listing.person.id", 
      "size": 10 
      }, 
      "aggs": { 
      "avg_standard": { 
       "avg": { 
       "field": "listing.ranking.position.standard" 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
} 

這給我帶來以下結果:

{ 
    "took": 1, 
    "timed_out": false, 
    "_shards": { 
    "total": 5, 
    "successful": 5, 
    "failed": 0 
    }, 
    "hits": { 
    "total": 2, 
    "max_score": 0, 
    "hits": [] 
    }, 
    "aggregations": { 
    "nest": { 
     "doc_count": 4, 
     "persons": { 
     "doc_count_error_upper_bound": 0, 
     "sum_other_doc_count": 0, 
     "buckets": [ 
      { 
      "key": 42, 
      "doc_count": 2, 
      "avg_standard": { 
       "value": 3.5 
      } 
      }, 
      { 
      "key": 55, 
      "doc_count": 2, 
      "avg_standard": { 
       "value": 6.5 
      } 
      } 
     ] 
     } 
    } 
    } 
} 

它似乎是正確的。

+0

非常感謝。生成的默認映射: 「列表」:{ 「屬性」:{...} } 但是,您是如何查詢它的,以得到完全的結果? – McClane

+0

@McClane如果它爲你工作,檢查這是接受;) –

+0

感謝一堆!正是我在找什麼。 – McClane