2015-09-23 30 views
0

我Elasticsearch有這樣的文檔的索引:Elasticsearch:總稱爲對象鍵(不是值)

[{ 
    "_index": "products", 
    "_type": "product", 
    "_id": "100", 
    "_score": 1, 
    "_source": { 
    "id": "100", 
    "name": "Product 1", 
    "catalogue": { 
     "categories": { 
     "cat1": ['h1', 'spin2'], 
     "cat5": ['h2', 'spin2'] 
     } 
    } 
    } 
}, 
{ 
    "_index": "products", 
    "_type": "product", 
    "_id": "100", 
    "_score": 1, 
    "_source": { 
    "id": "100", 
    "name": "Product 1", 
    "catalogue": { 
     "categories": { 
     "cat2": ['d1', 'spin2'], 
     "cat5": ['h2', 'spin2'] 
     } 
    } 
    } 
}] 

我需要聚合known categories。以上的預期結果是:

"aggregations": { 
    "categories": { 
    "doc_count_error_upper_bound": 0, 
    "sum_other_doc_count": 0, 
    "buckets": [ 
     { 
     "key": "cat1", 
     "doc_count": 1 
     }, 
     { 
     "key": "cat2", 
     "doc_count": 1 
     }, 
     { 
     "key": "cat5", 
     "doc_count": 2 
     }, 
    ] 
    } 
} 

我該如何定義我的搜索調用?

GET _search 
{ 
    "aggregations": { 
    "categories": { 
     "terms": { 
     ??? 
     } 
    } 
    } 
} 

UPDATE: 我也許應該使用script鍵像下面。這可能會對性能產生影響,對吧?

GET _search 
{ 
    "aggregations": { 
    "categories": { 
     "terms": { 
     "script" : "????" 
     } 
    } 
    } 
+0

你可以提供'catalogue'的完整映射嗎? –

+0

@AndreiStefan這就是我現在所擁有的一切。將來我會添加其他鍵,因此我不能更改結構。謝謝。 – xpepermint

+0

你爲什麼拒絕投票? – xpepermint

回答

0

你可以做這樣的事情

GET /products/product/_search?search_type=count 
{ 
    "aggs": { 
    "cats": { 
     "terms": { 
     "script": "categories=_source.catalogue.categories;terms=[];for(categ in categories.keySet())terms+=categ;return terms" 
     } 
    } 
    } 
} 

但是,是的,它會影響性能。你需要測試這個,看看它的行爲。確保你多次運行相同的查詢,因爲第一次可能需要更長的時間才能返回,這是正常的。