用groovy指令碼自定義ElasticSearch查詢,來實現以上功能。 例,資料中包含欄位birdtyday,記錄遊客生日: "birthday": "1992-02-05 00:00:00", 新建檔案getAgeByBirthday.groovy,編輯其內容為: def b = doc[birthday_field].value def birthday = new Date(b) def now = new Date() long age = (now -birthday)/365 age 並把此檔案放在es的config/scripts目錄下(如果沒有此目錄就新建一個)。 然後在config/elasticsearch.yml檔案中加一行: script.groovy.sandbox.enabled: true 最後重啟es即可。 接下來,我們就可以用以下DSL進行年齡統計了 GET /lovingtrip-report/hotelcustomer/_search?search_type=count { "aggs": { "counts_by_age": { "terms": { "script_file": "getAgeByBirthday", "params": { "birthday_field": "birthday" }, "size": 100 } } } } 或者: GET /lovingtrip-report/hotelcustomer/_search?search_type=count { "aggs": { "histogram_by_age": { "histogram": { "script_file": "getAgeByBirdthday", "params": { "birdthday_field": "birdthday" }, "interval": 5 } } } } 不過指令碼查詢效能不佳,且不能利用es的快取,所以在大資料量或高效能要求的場景下不適用。。 ------------------------------------- 補充一個自定義的年齡range過濾: range_AgeByBirthday.groovy: def b = doc[birdthday_field].value def birdthday = new Date(b) def now = new Date() long age = (now -birdthday)/365 gte<=age && age<=lte DSL: GET /lovingtrip-report/hotelcustomer/_search?search_type=count { "query": { "filtered": { "filter": { "script": { "script_file": "range_AgeByBirdthday", "params": { "birdthday_field": "birdthday", "gte": 50, "lte": 60 } } } } }, "aggs": { "histogram_by_age": { "histogram": { "script_file": "getAgeByBirdthday", "params": { "birdthday_field": "birdthday" }, "interval": 5 } } } }
用groovy指令碼自定義ElasticSearch查詢,來實現以上功能。 例,資料中包含欄位birdtyday,記錄遊客生日: "birthday": "1992-02-05 00:00:00", 新建檔案getAgeByBirthday.groovy,編輯其內容為: def b = doc[birthday_field].value def birthday = new Date(b) def now = new Date() long age = (now -birthday)/365 age 並把此檔案放在es的config/scripts目錄下(如果沒有此目錄就新建一個)。 然後在config/elasticsearch.yml檔案中加一行: script.groovy.sandbox.enabled: true 最後重啟es即可。 接下來,我們就可以用以下DSL進行年齡統計了 GET /lovingtrip-report/hotelcustomer/_search?search_type=count { "aggs": { "counts_by_age": { "terms": { "script_file": "getAgeByBirthday", "params": { "birthday_field": "birthday" }, "size": 100 } } } } 或者: GET /lovingtrip-report/hotelcustomer/_search?search_type=count { "aggs": { "histogram_by_age": { "histogram": { "script_file": "getAgeByBirdthday", "params": { "birdthday_field": "birdthday" }, "interval": 5 } } } } 不過指令碼查詢效能不佳,且不能利用es的快取,所以在大資料量或高效能要求的場景下不適用。。 ------------------------------------- 補充一個自定義的年齡range過濾: range_AgeByBirthday.groovy: def b = doc[birdthday_field].value def birdthday = new Date(b) def now = new Date() long age = (now -birdthday)/365 gte<=age && age<=lte DSL: GET /lovingtrip-report/hotelcustomer/_search?search_type=count { "query": { "filtered": { "filter": { "script": { "script_file": "range_AgeByBirdthday", "params": { "birdthday_field": "birdthday", "gte": 50, "lte": 60 } } } } }, "aggs": { "histogram_by_age": { "histogram": { "script_file": "getAgeByBirdthday", "params": { "birdthday_field": "birdthday" }, "interval": 5 } } } }