Painless Script | 简介
- 自 ElasticSearch 5.0 引入,专门为 ElasticSearch 设计,扩展了 Java 的语法;
- 6.0 开始,ElasticSearch 只支持 Painless,Groovy,JavaScript 和 Python 都不再支持;
- Painless 支持所有 Java 的数据类型和 Java API 子集;
Painless Script 具备以下特性:
Painless Script | 用途
- 可以对文档字段进行加工处理:
- 更新或删除字段,处理数据聚合操作;
- Script Field:对返回的字段提前进行计算;
- Function Score:对文档的算分进行处理;
- 在 Ingest Pipeline 中执行脚本;
- 在 Reindex API,Update By Query 时,对数据进行处理;
Painless Script | 访问字段
上下文 | 语法 |
---|
Ingest | ctx.field_name |
Update | ctx._source.field_name |
Search & Aggregation | doc["field_name"] |
脚本缓存
使用脚本的开销还是挺大的,ElasticSearch 会将脚本编译后缓存在 Cache 中,Inline scripts 和 Stored Scripts 都会被缓存;ElasticSearch 默认缓存 100 个脚本;
参数 | 说明 |
---|
script.cache.max_size | 设置最大缓存数 |
script.cache.expire | 设置缓存超时 |
script.max_compilations_rate | 默认 5 分钟最多 75 次编译 |
Painless Script | 举几个栗子
计算 content 字段的长度 | 增加 views 字段的默认值
POST _ingest/pipeline/_simulate
{
"pipeline": {
"description": "to split blog tags",
"processors": [
{
"split": {
"field": "tags",
"separator": ","
}
},
{
"script": {
"source": """
if(ctx.containsKey("content")){
ctx.content_length = ctx.content.length();
}else{
ctx.content_length=0;
}
"""
}
},
{
"set":{
"field": "views",
"value": 0
}
}
]
},
"docs": [
{
"_index":"index",
"_id":"id",
"_source":{
"title":"Introducing big data......",
"tags":"hadoop,elasticsearch,spark",
"content":"You konw, for big data"
}
},
{
"_index":"index",
"_id":"idxx",
"_source":{
"title":"Introducing cloud computering",
"tags":"openstack,k8s",
"content":"You konw, for cloud"
}
}
]
}
使用 Painless Script 更新文档
DELETE tech_blogs
PUT tech_blogs/_doc/1
{
"title":"Introducing big data......",
"tags":"hadoop,elasticsearch,spark",
"content":"You konw, for big data",
"views":0
}
POST tech_blogs/_update/1
{
"script": {
"source": "ctx._source.views += params.new_views",
"params": {
"new_views":100
}
}
}
保存 Painless Script 到 Cluster State 中
POST _scripts/update_views
{
"script":{
"lang": "painless",
"source": "ctx._source.views += params.new_views"
}
}
使用保存的 Painless Script 更新文档
POST tech_blogs/_update/1
{
"script": {
"id": "update_views",
"params": {
"new_views":1000
}
}
}
为查询结果增加脚本字段
GET tech_blogs/_search
{
"script_fields": {
"rnd_views": {
"script": {
"lang": "painless",
"source": """
java.util.Random rnd = new Random();
doc['views'].value+rnd.nextInt(1000);
"""
}
}
},
"query": {
"match_all": {}
}
}