2017-07-03 254 views
2

如何計算滿足ElasticSearch中的特定條件的嵌套字段(它是嵌套對象列表)的對象?ElasticSearch計數嵌套字段

有客戶指標,與具有以下結構的服務嵌套的字段類型的客戶:

public class Customer 
{ 
    public int Id; 
    public List<Service> Services; 
} 

public class Service 
{ 
    public int Id; 
    public DateTime Date; 
    public decimal Rating; 
} 

如何指望它發生在六月2017年得到了一個等級的所有服務高於5?

回答

1

好問題:) 爲了得到你想要的東西,你應該先定義你的映射,嵌套屬性映射效果很好。

嵌套類型是該對象的數據類型,它允許對象的數組被索引和查詢獨立的彼此的專用版本。 https://www.elastic.co/guide/en/elasticsearch/reference/2.4/nested.html

請在下面找到完整的例子:)

映射

PUT example_nested_test 
{ 
    "mappings": { 
    "nested": { 
     "properties": { 
     "Id": { 
      "type": "long" 
     }, 
     "Services": { 
      "type": "nested", 
      "properties": { 
      "Id": { 
       "type": "long" 
      }, 
      "Date": { 
       "type": "date" 
      }, 
      "Rating": { 
       "type": "long" 
      } 
      } 
     } 
     } 
    } 
    } 
} 

POST數據

POST example_nested_test/nested/100 
    { 
     "Id" : 1, 
     "Services": [ 
     { 
      "Id": 1, 
      "Date" :"2017-05-10", 
      "Rating" : 5 
     }, 
     { 
      "Id": 2, 
      "Date" :"2013-05-10", 
      "Rating" : 2 
     }, 
     { 
      "Id": 4, 
      "Date" :"2017-05-10", 
      "Rating" : 6 
     }] 
    } 

查詢

GET example_nested_test/_search 
{ 
    "size":0, 
    "aggs": { 
    "Services": { 
     "nested": { 
     "path": "Services" 
     }, 
     "aggs": { 
     "Rating": { 
      "filter": { 
      "bool": { 
       "must": [ 
       { 
        "range": { 
        "Services.Date": { 
         "gt": "2017", 
         "format": "yyyy" 
        } 
        } 
       }, 
       { 
        "range": { 
        "Services.Rating": { 
         "gt": "5" 
        } 
        } 
       } 
       ] 
      } 
      } 
     } 
     } 
    } 
    } 
} 

結果

"aggregations": { 
    "Services": { 
     "doc_count": 3, 
     "Rating": { 
     "doc_count": 1 
     } 
    } 
    }