2017-02-17 52 views
0

我有這個映射模型在我elasticsearch指數:Elasticsearch結果下令並分組BY

{ 
    "my_index": { 
    "mappings": { 
     "vehicules": { 
     "properties": { 
      "name": { 
      "type": "text" 
      }, 
      "category_id": { 
      "type": "integer" 
      }, 
      "price": { 
      "type": "float" 
      }, 
     } 
     } 
    } 
    } 
} 

在這個指標,我已經插入一些演示數據:

+--------------+-------------+-------+ 
|  Name  | Category ID | Price | 
+--------------+-------------+-------+ 
| Car 1  |   1 | 1500 | 
| Car 2  |   1 | 4000 | 
| Car 3  |   1 | 2500 | 
| Motorcycle 1 |   2 | 3000 | 
| Motorcycle 2 |   2 | 1400 | 
| Motorcycle 3 |   2 | 2700 | 
| Truck 1  |   3 | 19000 | 
| Truck 2  |   3 | 15000 | 
+--------------+-------------+-------+ 

我想根據價格值ASC對所有產品進行排序,並按類別對結果進行分組。類別本身必須用她的孩子數據的價格值進行排序。這給:

{ 
    "2": [  <= Category where the price start with lower price (1400) 
     { 
      "name": "Motorcycle 2", 
      "price": 1400 
     }, 
     { 
      "name": "Motorcycle 3", 
      "price": 2700 
     }, 
     { 
      "name": "Motorcycle 1", 
      "price": 3000 
     } 
    ], 
    "1": [ 
     { 
      "name": "Car 1", 
      "price": 1500 
     }, 
     { 
      "name": "Car 3", 
      "price": 2500 
     }, 
     { 
      "name": "Car 2", 
      "price": 4000 
     } 
    ], 
    "3": [ 
     { 
      "name": "Truck 2", 
      "price": 15000 
     }, 
     { 
      "name": "Truck 1", 
      "price": 19000 
     } 
    ] 
} 

是否有可能有類似的結果或與ES接近?我是ES的初學者,我在Kibana的DevTool中嘗試了許多不同的查詢,但都沒有成功。


我想我找到了具有所需結果的查詢。我不確定它是完全優化的,但它的工作原理。

GET my_index/my_type/_search 
{ 
    "size": 0, 
    "aggs": { 
    "grouped_by_cat": { 
     "terms": { 
     "field": "category_id", 
     "order": { 
      "min_price_aggs": "asc" 
     } 
     }, 
     "aggs": { 
     "min_price_aggs": { 
      "min": { 
      "field": "price" 
      } 
     }, 
     "list_top_hits": { 
      "top_hits": { 
      "_source": { 
       "includes": [ 
       "name", 
       "price" 
       ] 
      }, 
      "sort": [ 
       { 
       "price": { 
        "order": "asc" 
       } 
       } 
      ], 
      "size": 10000 
      } 
     } 
     } 
    } 
    } 
} 

此查詢看起來是否正確?

+0

哪個ElasticSearch的版本,您使用下面的查詢上述結果? –

+0

我使用ES v5.2。我會更新可能回答一個查詢,返回我想要的結果。 – Gaius

回答

0

因此可以實現通過

GET my_index/vehicles/_search 
{ 
"size": 0, 
"aggs" : { 
    "category_id_aggs": { 
     "terms" : { 
      "field" : "category_id" 
     }, 
     "aggs": { 
      "data": { 
       "top_hits": { 
        "size": 10, 
        "sort": [{"price":"asc"}], 
        "_source": { 
         "includes" : ["name","price"] 
        } 
       } 
      } 
     } 
    } 
    } 
}