我在 Elasticsearch 中的每條記錄都有一個物件陣列,如下所示:
{
"counts_by_year": [
{
"year": 2022,
"works_count": 22523,
"cited_by_count": 18054
},
{
"year": 2021,
"works_count": 32059,
"cited_by_count": 24817
},
{
"year": 2020,
"works_count": 27210,
"cited_by_count": 30238
},
{
"year": 2019,
"works_count": 22592,
"cited_by_count": 33631
}
]
}
我想要做的是使用 works_count 的平均值對我的記錄進行排序,其中年份是 2022 年,年份是 2021 年。在這種情況下我可以使用基于腳本的排序嗎?或者我應該嘗試將這些值復制到一個單獨的欄位中并對其進行排序嗎?
編輯 - 映射是:
{
"mappings": {
"_doc": {
"properties": {
"@timestamp": {
"type": "date"
},
.
.
.
"counts_by_year": {
"properties": {
"cited_by_count": {
"type": "integer"
},
"works_count": {
"type": "integer"
},
"year": {
"type": "integer"
}
}
},
.
.
.
}
}
}
}
uj5u.com熱心網友回復:
Tldr;
這取決于。很可能是,除非count_by_year嵌套。
解決方案
沿著這些路線的東西應該可以解決問題
GET /_search
{
"sort": {
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": "doc['counts_by_year.works_count'].stream().mapToLong(x -> x).average().orElse(0);"
}
}
}
}
解決方案(嵌套欄位)
PUT 74404793-2
{
"mappings": {
"properties": {
"counts_by_year": {
"type": "nested",
"properties": {
"cited_by_count": {
"type": "long"
},
"works_count": {
"type": "long"
},
"year": {
"type": "long"
}
}
}
}
}
}
POST /74404793-2/_doc/
{
"counts_by_year": [
{
"year": 2022,
"works_count": 22523,
"cited_by_count": 18054
},
{
"year": 2021,
"works_count": 32059,
"cited_by_count": 24817
},
{
"year": 2020,
"works_count": 27210,
"cited_by_count": 30238
},
{
"year": 2019,
"works_count": 22592,
"cited_by_count": 33631
}
]
}
我正在使用_source訪問檔案,如果您有大檔案,它會嚴重影響性能。
GET 74404793-2/_search
{
"sort": {
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": """
params._source['counts_by_year']
.stream()
.filter(x -> x['year'] > 2020)
.mapToLong(x -> x['works_count'])
.average().orElse(0);"""
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537903.html
標籤:弹性搜索
