溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Scripting腳本的介紹和使用方法

發(fā)布時(shí)間:2021-06-30 15:30:59 來(lái)源:億速云 閱讀:396 作者:chen 欄目:大數(shù)據(jù)

這篇文章主要介紹“Scripting腳本的介紹和使用方法”,在日常操作中,相信很多人在Scripting腳本的介紹和使用方法問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Scripting腳本的介紹和使用方法”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

簡(jiǎn)介

官方7.9版本:https://www.elastic.co/guide/en/elasticsearch/reference/7.9/modules-scripting.html

通過ES腳本來(lái)解決,其允許用戶在一些特定的API中對(duì)自定義表達(dá)式進(jìn)行求值。

1. ES Scripting歷史

版本

使用腳本

< Elasticsearch 1.4

MVEL 腳本

< Elasticsearch 5.0

Groovy 腳本

‘>= Elasticsearch 5.0

painless 腳本

2. Painless Scripting 簡(jiǎn)介

Painless是一種簡(jiǎn)單,安全的腳本語(yǔ)言,專為與Elasticsearch一起使用而設(shè)計(jì)。它是Elasticsearch的默認(rèn)腳本語(yǔ)言,可以安全地用于內(nèi)聯(lián)和存儲(chǔ)腳本。

Painless特點(diǎn):

  • 性能優(yōu)秀:Painless腳本運(yùn)行速度比備選方案(包括Groovy)快幾倍。

  • 安全性強(qiáng):使用白名單來(lái)限制函數(shù)與字段的訪問,避免了可能的安全隱患。

  • 可選輸入:變量和參數(shù)可以使用顯式類型或動(dòng)態(tài)def類型。

  • 上手容易:擴(kuò)展了java的基本語(yǔ)法,并兼容groove風(fēng)格的腳本語(yǔ)言特性。

  • 特定優(yōu)化:是ES官方專為Elasticsearch腳本編寫而設(shè)計(jì)。

3. Scripting 應(yīng)用場(chǎng)景

增刪改查能解決業(yè)務(wù)場(chǎng)景80%的問題,Painless腳本操作一般應(yīng)用于相對(duì)復(fù)雜的業(yè)務(wù)場(chǎng)景中。

  • 自定義字段

  • 自定義評(píng)分

  • 自定義更新

  • 自定義reindex

  • 聚合

  • 其他自定義操作

在 update, update-by-query, 或 reindex API中使用腳本時(shí),需要通過ctx去訪問文檔中的字段。

ctx._source: 訪問文檔_source字段
ctx.op: 對(duì)文檔對(duì)應(yīng)的操作,包括index和delete
ctx._index : 訪問文檔的 meta-fields
其他字段或變量的訪問見: update context

4. Scripting 使用模板

"script": {
    "lang":   "...",  # 代表language腳本語(yǔ)言,默認(rèn)指定為:painless
    "source" | "id": "...",  # 腳本的核心部分,id應(yīng)用于:stored script
    "params": { ... }  # 傳遞給腳本使用的變量參數(shù)
  }

Scripting應(yīng)用

1. 自定義字段

如:需要給每個(gè)doc的complexrank字段翻倍并返回翻倍后的值

POST sphinx-doctor/_search
{
  "from": 0,
  "size": 20,
  "query": {
    "match_all": {}
  },
  "_source": "complexrank",
  "script_fields": {
    "custom_field": {
      "script": {
        "lang": "expression", # 這里腳本語(yǔ)言選擇的expression
        "source": "doc['complexrank'] * multiplier",
        "params": {
          "multiplier": 2
        }
      }
    }
  }
}
說明:對(duì)原索引中的complexrank字段值進(jìn)行2倍返回給custom_field字段

{
    "took":20,
    "timed_out":false,
    "_shards":{
        "total":1,
        "successful":1,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":194354,
        "max_score":1,
        "hits":[
            {
                "_index":"sphinx-doctor-20.11.06-103145",
                "_type":"_doc",
                "_id":"740",
                "_score":1,
                "_source":{
                    "complexrank":"5985"
                },
                "fields":{
                    "custom_field":[
                        11970
                    ]
                }
            },
            {
                "_index":"sphinx-doctor-20.11.06-103145",
                "_type":"_doc",
                "_id":"742",
                "_score":1,
                "_source":{
                    "complexrank":"5325"
                },
                "fields":{
                    "custom_field":[
                        10650
                    ]
                }
            }
        ]
    }
}

如:返回日期字段中的“年”或“月”或“日”等

POST drug/_search
{
  "from": 0,
  "size": 20,
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "custom_field": {
      "script": {
        "source": "doc.ctime.value.year" #月:month
      }
    }
  }
}

{
    "took":57,
    "timed_out":false,
    "_shards":{
        "total":1,
        "successful":1,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":173536,
        "max_score":1,
        "hits":[
            {
                "_index":"drug-20.12.03-151452",
                "_type":"_doc",
                "_id":"1883795984",
                "_score":1,
                "fields":{
                    "custom_field":[
                        2014
                    ]
                }
            },
            {
                "_index":"drug-20.12.03-151452",
                "_type":"_doc",
                "_id":"1883795985",
                "_score":1,
                "fields":{
                    "custom_field":[
                        2014
                    ]
                }
            }
        ]
    }
}

2. 自定義評(píng)分

POST sphinx-doctor/_search
{
  "from": 0,
  "size": 2,
  "_source": "hospitalname", 
  "query": {
    "function_score": {
      "query": {
        "match": {
          "hospitalname": {
            "query": "北京協(xié)和醫(yī)院"
          }
        }
      },
      "functions": [
        {
          "filter": {
            "match_all": {
              "boost": 1
            }
          },
          "script_score": {
            "script": {
              "source": "_score *params._score + doc['rank'].value * params.rank + doc['adminlevel'].value * params.adminlevel",
              "lang": "painless",  # # 是Lucene’s expressions 腳本語(yǔ)言
              "params": {
                "adminlevel": 2500,
                "rank": 0.5,
                "_score": 1
              }
            }
          }
        }
      ],
      "score_mode": "sum",
      "max_boost": 3.4028235e+38,
      "boost": 1
    }
  },
  "track_scores": true
}

{
  "took" : 487,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 777965,
    "max_score" : 449721.3,
    "hits" : [
      {
        "_index" : "sphinx-doctor-20.12.09-010000",
        "_type" : "_doc",
        "_id" : "175477",
        "_score" : 449721.3,
        "_source" : {
          "hospitalname" : "北京協(xié)和醫(yī)院"
        }
      },
      {
        "_index" : "sphinx-doctor-20.12.09-010000",
        "_type" : "_doc",
        "_id" : "221609",
        "_score" : 440269.34,
        "_source" : {
          "hospitalname" : "北京協(xié)和醫(yī)院"
        }
      }
    ]
  }
}

Java API:排序

String scriptText = "_score *params._score + doc['rank'].value * params.rank + doc['adminlevel'].value * params.adminlevel";

Map<String, Object> params = new HashMap<>();
params.put("_score", 1.0f);
params.put("rank", 0.5f);
params.put("adminlevel", 2500f);

Script script = new Script(ScriptType.INLINE, "painless", scriptText, params);

ScriptScoreFunctionBuilder scriptScoreFunctionBuilder = ScoreFunctionBuilders.scriptFunction(script);
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQueryBuilder, scriptScoreFunctionBuilder)
                        .scoreMode(FunctionScoreQuery.ScoreMode.SUM);

builder.query(functionScoreQueryBuilder);
builder.from(offset);
builder.size(limit);
//當(dāng)使用排序_sort 來(lái)指定依據(jù)某些字段排序。就不會(huì)計(jì)算得分,需要設(shè)置"track_scores":true,這樣分?jǐn)?shù)就會(huì)被計(jì)算和跟蹤。
builder.trackScores(true);

3. 自定義更新

update:將已有字段值賦值給其他字段。

POST sphinx-doctor/_doc/102647/_update
{
  "script": {
    "lang": "painless",
    "source": "ctx._source.hospitalname = params.hospitalname;ctx._source.name = params.name",
    "params": {
      "hospitalname": "北京協(xié)和醫(yī)院",
      "name": "協(xié)和醫(yī)生"
    }
  }
}

update_by_query

POST sphinx-doctor/_update_by_query
{
  "query": {
    "term": {
      "id": {
        "value": "102647"
      }
    }
  },
  "script": {
    "lang": "painless",
    "source": """
       if (ctx._source.registerordercount >= 500) {
          ctx._source.registerordercount += 200;
       } else {
          ctx.op = 1000;
      }
   """
  }
}

4.自定義reindex

POST _reindex
{
  "source": {
    "index": "sphinx-doctor-20.12.02-150616",
    "size": 4000
  },
  "dest": {
    "index": "sphinx-doctor-20.12.03-151452"
  },
  "script": {
    "source": "ctx._source.complexrank += 10;\nctx._source.netcaseprice = 100;"
  }
}

5. 聚合

POST sphinx-doctor/_search
{
  "from": 0,
  "size": 20, 
  "query": {
    "match": {
      "hospitalname": "北京協(xié)和醫(yī)院"
    }
  },
  "aggs": {
    "grade": {
      "terms": {
        "script": {
          "source": "doc['grade.keyword'].value",
          "lang": "painless"
        }
      }
    }
  }
}

{
  "took" : 187,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 193445,
    "max_score" : 44.18691,
    "hits" : [
      {
        "_index" : "sphinx-doctor-20.11.06-103145",
        "_type" : "_doc",
        "_id" : "30626487346",
        "_score" : 44.18691,
        "_source" : {
          "registerordercount" : 0,
          "hospitalfacultyname" : "神經(jīng)內(nèi)科",
          "idx_doctoridprimary" : "DoctorIdPrimary_335",
          "hospitaldistrict" : "東城",
          "caseopened" : true,
          "isonline" : null,
          "dummy" : "SELECT_ALL",
          "facultyid" : "1007000",
          "price" : "10",
          "rank" : "0",
          "ctime" : "1568269475",
          "id" : "30626487346",
          "clinicprice" : "20.00",
          "idx_hospitalfacultyid" : "HospitalFacultyId_335",
          "educategrade" : "",
          "adminlevel" : "1",
          "isprimarydoctor" : 1,
          "isexpert" : true,
          "bookingvisitnum" : 0,
          "primaryid" : "30626487346",
          "hospitalfacultyid" : "335",
          "spaceid" : "200007660088",
          "hospitalcity" : "北京",
          "isopenvideo" : true,
          "grade" : "主任醫(yī)師",
          "name" : "3 0626487346",
          "idx_fix_bigcity" : "北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院測(cè)試用",
          "phoneopened" : true,
          "onlineschedule" : "20201207,20201214,20201221",
          "isvideotpl" : false,
          "issanjia" : true,
          "hospitalprovince" : "北京",
          "servicelevel" : 2,
          "title" : "",
          "confirmed" : "1",
          "isvip" : false,
          "general" : 0,
          "menzhenprice" : "10",
          "isopencosvideo" : false,
          "hospitalname" : "北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院測(cè)試用",
          "netcaseprice" : "20.00",
          "registrprice" : 0,
          "free" : 0,
          "workstatus" : "0",
          "registtationopened" : null,
          "indextype" : "doctor",
          "utime" : 1606978403,
          "complexrank" : "5985",
          "sex" : "1",
          "reservationopened" : null,
          "idx_doctorid" : "DoctorId_30626487346",
          "idx_hospital_info" : "北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院北京協(xié)和醫(yī)院測(cè)試用,北京協(xié)和醫(yī)院,33北京協(xié)和醫(yī)院,協(xié)和醫(yī)院,協(xié)和東院,協(xié)和東院區(qū),北京協(xié)和醫(yī)院東院,協(xié)和西院,北京郵電總醫(yī)院,郵電總醫(yī)院,北京協(xié)和西院,北京協(xié)和醫(yī)院西院區(qū),北京協(xié)和醫(yī)院西院,北京協(xié)和,北京市協(xié)和,北京郵電醫(yī)院,協(xié)合醫(yī)院,北京市協(xié)和醫(yī)院,中國(guó)醫(yī)學(xué)科學(xué)院北京協(xié)和醫(yī)院,北京協(xié)合醫(yī)院45,協(xié)和醫(yī)院,北京協(xié)和,北京市協(xié)和,協(xié)和東院,北京協(xié)和醫(yī)院東院,協(xié)和西院,北京郵電醫(yī)院,北京協(xié)和西院,北京協(xié)和醫(yī)院西院,協(xié)合醫(yī)院,北京市協(xié)和醫(yī)院,中國(guó)醫(yī)學(xué)科學(xué)院北京協(xié)和醫(yī)院,北京協(xié)合醫(yī)院",
          "isopenrecipe" : false,
          "hits" : "0",
          "iscosmetologydoctor" : null,
          "hospitalid" : "1",
          "idx_facultyid" : "FacultyId_1007000",
          "activitytime" : "1568269520",
          "hospitalgrade" : "6",
          "idx_hospitalid" : "HospitalId_1",
          "username" : "francoliu"
        }
      },
      {
        "_index" : "sphinx-doctor-20.11.06-103145",
        "_type" : "_doc",
        "_id" : "310346050824",
        "_score" : 40.138744,
        "_source" : {
          "registerordercount" : 0,
          "hospitalfacultyname" : "心血管內(nèi)科",
          "idx_doctoridprimary" : "DoctorIdPrimary_341",
          "hospitaldistrict" : "東城",
          "caseopened" : false,
          "isonline" : null,
          "dummy" : "SELECT_ALL",
          "facultyid" : "1010000",
          "price" : 0,
          "rank" : "0",
          "ctime" : "1605859848",
          "id" : "310346050824",
          "clinicprice" : 0,
          "idx_hospitalfacultyid" : "HospitalFacultyId_341",
          "educategrade" : "教授",
          "adminlevel" : "4",
          "isprimarydoctor" : 1,
          "isexpert" : true,
          "bookingvisitnum" : 0,
          "primaryid" : "310346050824",
          "hospitalfacultyid" : "341",
          "spaceid" : "0",
          "hospitalcity" : "北京",
          "isopenvideo" : null,
          "grade" : "主任醫(yī)師",
          "name" : "地名",
          "idx_fix_bigcity" : "北京協(xié)和醫(yī)院",
          "phoneopened" : false,
          "onlineschedule" : "",
          "isvideotpl" : false,
          "issanjia" : true,
          "hospitalprovince" : "北京",
          "servicelevel" : 0,
          "title" : "",
          "confirmed" : "",
          "isvip" : false,
          "general" : 0,
          "menzhenprice" : 0,
          "isopencosvideo" : false,
          "hospitalname" : "北京協(xié)和醫(yī)院",
          "netcaseprice" : 0,
          "registrprice" : 0,
          "free" : 0,
          "workstatus" : "0",
          "registtationopened" : null,
          "indextype" : "doctor",
          "utime" : 1605859882,
          "complexrank" : "0",
          "sex" : "1",
          "reservationopened" : null,
          "idx_doctorid" : "DoctorId_310346050824",
          "idx_hospital_info" : "北京協(xié)和醫(yī)院,北京協(xié)和醫(yī)院,33北京協(xié)和醫(yī)院,協(xié)和醫(yī)院,協(xié)和東院,協(xié)和東院區(qū),北京協(xié)和醫(yī)院東院,協(xié)和西院,北京郵電總醫(yī)院,郵電總醫(yī)院,北京協(xié)和西院,北京協(xié)和醫(yī)院西院區(qū),北京協(xié)和醫(yī)院西院,北京協(xié)和,北京市協(xié)和,北京郵電醫(yī)院,協(xié)合醫(yī)院,北京市協(xié)和醫(yī)院,中國(guó)醫(yī)學(xué)科學(xué)院北京協(xié)和醫(yī)院,北京協(xié)合醫(yī)院45,協(xié)和醫(yī)院,北京協(xié)和,北京市協(xié)和,協(xié)和東院,北京協(xié)和醫(yī)院東院,協(xié)和西院,北京郵電醫(yī)院,北京協(xié)和西院,北京協(xié)和醫(yī)院西院,協(xié)合醫(yī)院,北京市協(xié)和醫(yī)院,中國(guó)醫(yī)學(xué)科學(xué)院北京協(xié)和醫(yī)院,北京協(xié)合醫(yī)院",
          "isopenrecipe" : null,
          "hits" : "0",
          "iscosmetologydoctor" : null,
          "hospitalid" : "1",
          "idx_facultyid" : "FacultyId_1010000",
          "activitytime" : null,
          "hospitalgrade" : "6",
          "idx_hospitalid" : "HospitalId_1",
          "username" : ""
        }
      }
    ]
  },
  "aggregations" : {
    "grade" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 479,
      "buckets" : [
        {
          "key" : "主任醫(yī)師",
          "doc_count" : 77699
        },
        {
          "key" : "副主任醫(yī)師",
          "doc_count" : 72939
        },
        {
          "key" : "主治醫(yī)師",
          "doc_count" : 20399
        },
        {
          "key" : "",
          "doc_count" : 13558
        },
        {
          "key" : "住院醫(yī)師",
          "doc_count" : 5731
        },
        {
          "key" : "副主任技師",
          "doc_count" : 896
        },
        {
          "key" : "副主任藥師",
          "doc_count" : 612
        },
        {
          "key" : "主管技師",
          "doc_count" : 468
        },
        {
          "key" : "主任藥師",
          "doc_count" : 355
        },
        {
          "key" : "副主任檢驗(yàn)師",
          "doc_count" : 309
        }
      ]
    }
  }
}

6.自定義排序

兩個(gè)或多個(gè)字段進(jìn)行運(yùn)算返回一個(gè)值進(jìn)行排序

POST sphinx-doctor/_search
{
  "_source": [
    "clinicprice",
    "menzhenprice"
  ],
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "number",  # string
      "order": "desc",
      "script": {
        "lang": "painless",
        "source": "doc['clinicprice'].value + doc['menzhenprice'].value"
      }
    }
  }
}

{
  "took" : 334,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 782852,
    "max_score" : null,
    "hits" : [
      {
        "_index" : "sphinx-doctor-20.12.09-010000",
        "_type" : "_doc",
        "_id" : "102647",
        "_score" : null,
        "_source" : {
          "menzhenprice" : "1400",
          "clinicprice" : "2700.00"
        },
        "sort" : [
          4100.0
        ]
      },
      {
        "_index" : "sphinx-doctor-20.12.09-010000",
        "_type" : "_doc",
        "_id" : "8231",
        "_score" : null,
        "_source" : {
          "menzhenprice" : "2000.00",
          "clinicprice" : "2000.00"
        },
        "sort" : [
          4000.0
        ]
      }
    ]
  }
}

邏輯運(yùn)算符進(jìn)行判斷來(lái)影響排序

POST sphinx-doctor/_search
{
  "_source": [
    "clinicprice",
    "menzhenprice"
  ],
  "from": 0,
  "size": 2, 
  "query": {
    "match_all": {}
  },
   "sort": [
    {
      "complexrank": {
        "order": "desc"
      }
    },
    {
      "_script": {
        "script": {
          "inline": "'北京 '==doc['hospitalprovince.keyword'].value?0:('陜西'==doc['hospitalprovince.keyword'].value?1:2)"
        },
        "type": "number",
        "order": "asc"
      }
    }
  ]
}

{
  "took" : 80,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 782852,
    "max_score" : null,
    "hits" : [
      {
        "_index" : "sphinx-doctor-20.12.09-010000",
        "_type" : "_doc",
        "_id" : "5279893112",
        "_score" : null,
        "_source" : {
          "menzhenprice" : "500",
          "clinicprice" : 0
        },
        "sort" : [
          981,
          2.0
        ]
      },
      {
        "_index" : "sphinx-doctor-20.12.09-010000",
        "_type" : "_doc",
        "_id" : "124096",
        "_score" : null,
        "_source" : {
          "menzhenprice" : "200.00",
          "clinicprice" : "200.00"
        },
        "sort" : [
          980,
          2.0
        ]
      }
    ]
  }
}

到此,關(guān)于“Scripting腳本的介紹和使用方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI