GET /your_index/_search
{
"query": { "match_all": {} },
"sort": [
{
"_script": {
"type": "number",
"script": {
"source": "doc['field1'].value + doc['field2'].value",
"lang": "painless"
},
"order": "desc" // 降序排列
}
}
]
}
若字段可能为空或非数值类型,则添加容错逻辑
GET /your_index/_search
{
"query": { "match_all": {} },
"sort": [
{
"_script": {
"type": "number",
"script": {
"source": "(doc['field1'].size() > 0 ? doc['field1'].value : 0) + (doc['field2'].size() > 0 ? doc['field2'].value : 0)",
"lang": "painless"
},
"order": "desc"
}
}
]
}
对于高频查询,可启用脚本缓存提升性能
POST _scripts/sum_script
{
"script": {
"lang": "painless",
"source": "doc[params.fieldname1].value + doc[params.fieldname2].value"
}
}
GET /your_index/_search
{
"query": { "match_all": {} },
"sort": [
{
"_script": {
"type": "number",
"script": {
"id": "sum_script", // 存储脚本的ID
"params": {
"fieldname1": "price",
"fieldname2": "tax"
}
},
"order": "desc"
}
}
]
}
定制化过滤数据
查找满足以下任一条件的文档:
1.资产峰值 >净资产 * 200%
2.市值 >持仓市值 * 150%
POST /your_index/_search
{
"query": {
"bool": {
"should": {
"script": {
"script": {
"inline": "doc['zichan_max'].value>doc['jinzichan'].value*2",
"lang": "painless"
},
"script": {
"inline": "doc['shizhi'].value>doc['holding_shizhi'].value*1.5",
"lang": "painless"
}
}
}
}
}
}