关于painless
- 支持 Java 及 Java 子集
- 6.0开始,不支持 Python,JS、Groovy等
- 高性能,安全
不同上下文访问字段的方法
上下文 | 语法 |
---|
Ingest | ctx.field_name |
Update | ctx._source.field_name |
Search && Aggregation | doc[“field_name”] |
Demo
Ingest
POST _ingest/pipeline/_simulate
{
"pipeline": {
"description": "to split blog tags",
"processors": [
{
"script": {
"source": """
if(!ctx.containsKey("is_vip")){
ctx.is_vip = 0;
}
"""
}
},
{
"script": {
"source": """
if(!ctx.containsKey("name")||ctx.name==null){
ctx.name = "None";
}
"""
}
}
]
},
"docs": [
{
"_index": "blog",
"_id": "id",
"_source": {
}
}
]
}
# 为ES添加一个 Pipeline
PUT _ingest/pipeline/blog_pipeline
{
"description": "a blog pipeline",
"processors": [
{
"script": {
"source": """
if(!ctx.containsKey("is_vip")){
ctx.is_vip = 0;
}
"""
}
},
{
"script": {
"source": """
if(!ctx.containsKey("name")||ctx.name==null){
ctx.name = "None";
}
"""
}
}
]
}
#查看Pipleline
GET _ingest/pipeline/blog_pipeline
#测试pipeline
POST _ingest/pipeline/blog_pipeline/_simulate
{
"docs": [
{
"_source": {
}
}
]
}
#不使用pipeline更新数据
PUT test_blogs/_doc/1
{
"name":null
}
#使用pipeline更新数据
PUT test_blogs/_doc/2?pipeline=blog_pipeline
{
"name":null
}
#查看两条数据,一条被处理,一条未被处理
POST test_blogs/_search
{}
update
#增加update_by_query的条件
POST test_blogs/_update_by_query?pipeline=blog_pipeline
{
"query": {
"term": {
"name": {
"value": "jim"
}
}
}
}
POST test_blogs/_search
{
"query": {
"term": {
"name": {
"value": "jim"
}
}
}
}
POST test_blogs/_update/1
{
"script": {
"source": "ctx._source.views += params.new_views",
"params": {
"new_views":100
}
}
}
# 查看views计数
POST test_blogs/_search
{
}
#保存脚本在 Cluster State
POST _scripts/update_views
{
"script":{
"lang": "painless",
"source": "ctx._source.views += params.new_views"
}
}
POST test_blogs/_update/1
{
"script": {
"id": "update_views",
"params": {
"new_views":1000
}
}
}
search
GET test_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": {}
}
}