2016-06-24 127 views
0

我有以下設置documnets
的有什麼辦法,我們可以使彈性搜索嵌套直方圖搜索
嵌套直方圖查詢在ElasticSearch

{"id": 1, "regions" : 111, "category" : 6, "Price" : 957} 
{"id": 2, "regions" : 111, "category" : 6, "Price" : 829} 
{"id": 3, "regions" : 111, "category" : 7, "Price" : 123} 
{"id": 4, "regions" : 111, "category" : 7, "Price" : 129} 
{"id": 5, "regions" : 111, "category" : 8, "Price" : 351} 
{"id": 6, "regions" : 111, "category" : 8, "Price" : 225} 

{"id": 7, "regions" : 112, "category" : 6, "Price" : 625} 
{"id": 8, "regions" : 112, "category" : 6, "Price" : 599} 
{"id": 9, "regions" : 112, "category" : 7, "Price" : 256} 
{"id": 10, "regions" : 112, "category" : 7, "Price" : 129} 
{"id": 11, "regions" : 112, "category" : 8, "Price" : 333} 
{"id": 12, "regions" : 112, "category" : 8, "Price" : 444} 
{"id": 13, "regions" : 112, "category" : 9, "Price" : 199} 
{"id": 14, "regions" : 112, "category" : 9, "Price" : 149} 
{"id": 15, "regions" : 112, "category" : 5, "Price" : 299} 
{"id": 16, "regions" : 112, "category" : 5, "Price" : 349} 

我需要做一個查詢(可能是一些嵌套直方圖或其他)獲得以下格式的輸出
每個地區應該有最低價格的不同類別。

[{ 
     "regions" : 111, 
     [{ 
       "category" : 6, 
       "Price" : 829 
      }, { 
       "category" : 7, 
       "Price" : 123 
      }, { 
       "category" : 8, 
       "Price" : 225 
      } 
     ] 
    }, { 
     "regions" : 112, 
     [{ 
       "category" : 6, 
       "Price" : 599 
      }, { 
       "category" : 7, 
       "Price" : 129 
      }, { 
       "category" : 8, 
       "Price" : 333 
      }, { 
       "category" : 9, 
       "Price" : 149 
      }, { 
       "category" : 5, 
       "Price" : 299 
      } 
     ] 
    }, 
] 

提前THX

回答

0

歡迎StackOverflow上。 ElasticSearch不會完全按照您指定的格式吐出數據。您需要使用查詢來篩選要查找的結果,然後遍歷每個將所需數據放入所需結構的結果。

0

您可以使用_bulk API對數據編制索引。事情是這樣的:

$ curl -XPOST localhost:9200/my_index/data/_bulk -d '{"index":{"_id":"1"}} 
{"regions" : 111, "category" : 6, "Price" : 957} 
{"index":{"_id":"2"}} 
{"regions" : 111, "category" : 6, "Price" : 829} 
{"index":{"_id":"3"}} 
{"regions" : 111, "category" : 7, "Price" : 123} 
{"index":{"_id":"4"}} 
{"regions" : 111, "category" : 7, "Price" : 129} 
{"index":{"_id":"5"}} 
{"regions" : 111, "category" : 8, "Price" : 351} 
{"index":{"_id":"6"}} 
{"regions" : 111, "category" : 8, "Price" : 225} 
' 

空白行與_bulk端點重要的,所以我用它的方式是很故意的。

那麼你將有一個映射與regionscategoryPrice索引爲long值的指數。從那裏,你可以使用一個聚合得到你要求的直方圖:

$ curl -XGET localhost:9200/my_index/_search -d '{ 
    "aggs": { 
    "group_by_region": { 
     "terms": { 
     "field": "regions", 
     "size": 10 
     }, 
     "aggs": { 
     "group_by_category": { 
      "terms": { 
      "field": "category", 
      "size": 10 
      }, 
      "min_price": { 
      "min": { 
       "field": "Price" 
      } 
      } 
     } 
     } 
    } 
    } 
}' 

這不會給你硬是把它的輸出,但它會給你,你要找的值對於。注意:我選擇了任意大小。此外,像「group_by_region」這樣的名字取決於你;他們是你會在響應中看到的,並且名字完全是任意的。