elasticsearch使用painless的一些簡(jiǎn)單例子

1、背景

此篇文檔僅僅是簡(jiǎn)單的記錄一下painless的一些簡(jiǎn)單的例子,防止以后忘記,不過多涉及painless的語法。

2、準(zhǔn)備數(shù)據(jù)

2.1 mapping

PUT /index_person
{
  "mappings": {
    "properties": {
      "name": {
        "type": "keyword"
      },
      "age": {
        "type": "integer"
      },
      "province": {
        "type": "keyword"
      }
    }
  }
}

2.2 插入數(shù)據(jù)

PUT /index_person/_bulk
{"index":{"_id":1}}
{"name":"張三","age":20,"province":"湖北"}
{"index":{"_id":2}}
{"name":"李四","age":25,"province":"北京"}
{"index":{"_id":3}}
{"name":"王五","age":30,"province":"湖南"}

3、例子

3.1 (update)更新文檔 id=1 的文檔,將 age 加 2歲

POST index_person/_update/1
{
  "script": {
    "lang": "painless",
    "source": """
      ctx['_source']['age'] += params['incrAge']
    """,
    "params": {
      "incrAge": 2
    }
  }
}

3.2 (update_by_query)如果 province 是北京的話,就將 age 減少1歲

POST index_person/_update_by_query
{
  "query": {
    "term": {
      "province": {
        "value": "北京"
      }
    }
  },
  "script": {
    "lang": "painless",
    "source": """
      ctx['_source']['age'] -= params['decrAge']
    """,
    "params": {
      "decrAge": 1
    }
  }
}

3.3 (ctx.op)如果張三的年齡小于20歲就不處理,否則就刪除這個(gè)文檔

POST index_person/_update/1
{
  "script": {
    "lang": "painless",
    "source": """
      // 這是默認(rèn)值,表示的是更新值,重新索引記錄
      ctx.op = 'index';
      if(ctx._source.age < 20){
        // 表示不處理
        ctx.op = 'none';
      }else{
        // 表示刪除這個(gè)文檔
       ctx.op = 'delete'; 
      }
    """
  }
}

3.4 (stored script)如果是湖南省則增加地市字段,值為長(zhǎng)沙

3.4.1 創(chuàng)建存儲(chǔ)腳本

PUT _scripts/add_city
{
  "script":{
    "lang": "painless",
    "source": "ctx._source.city = params.city"
  }
}

add_city為腳本的id

3.4.2 使用存儲(chǔ)腳本

POST index_person/_update_by_query
{
  "query": {
    "term": {
      "province": {
        "value": "湖南"
      }
    }
  },
  "script": {
    "id": "add_city",
    "params": {
      "city": "長(zhǎng)沙"
    }
  }
}

3.5 (pipeline)通過pipeline如果插入的文檔的age<10則放入到index_person_small索引中

3.5.1 創(chuàng)建pipeline

PUT _ingest/pipeline/pipeline_index_person_small
{
  "description": "如果插入的文檔的age<10則放入到index_person_small索引中",
  "processors": [
    {
      "script": {
        "source": """
            if(ctx.age < 10){
              ctx._index = 'index_person_small';
            }
          """
      }
    }
  ]
}

3.5.2 使用pipeline

PUT index_person/_doc/4?pipeline=pipeline_index_person_small
{
  "name":"趙六",
  "age": 8,
  "province":"四川"
}

3.5.3 運(yùn)行結(jié)果

運(yùn)行結(jié)果

3.6 function_score中使用script_score算分

3.6.1 需求

如果這個(gè)用戶是湖南的,則使用 age作為分?jǐn)?shù)

3.6.2 dsl

GET index_person/_search
{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "script_score": {
            
            "script": """
              if(doc.province.value == 0){
                return 0;
              }
            
              if(doc.province.value == '湖南'){
                return doc.age.value;
              }
              return 0;
            """
          }
        }
      ],
      "boost_mode": "sum",
      "score_mode": "sum"
    }
  }
}

3.6.3 運(yùn)行結(jié)果

運(yùn)行結(jié)果

3.7 script_fields 增加字段

GET index_person/_search
{
  "query": {"match_all": {}},
  "fields": [
    "double_age"
  ], 
  "script_fields": {
    "double_age": {
      "script": {
        "lang": "painless",
        "source": "doc.age.value * 2"
      }
    }
  }
}

3.8 runtime field 增加字段

3.8.1 需求

針對(duì)age<25的文檔,返回double_age字段,否則不處理。

3.8.2 dsl

GET index_person/_search
{
  "query": {
    "match_all": {}
  },
  "fields": [
    "double_age"
  ],
  "runtime_mappings": {
    "double_age":{ 
      "type": "keyword",
      "script": """
        if(doc.age.size() == 0){
          return;
        }
        if(doc.age.value < 25){
          emit(doc.age.value * 2 + '');
        }
      """
    }
  }
}

在runtime field 中,需要使用emit來返回?cái)?shù)據(jù),但是不是emit(null)

3.9 _reindex 中使用

3.9.1 dsl

POST _reindex
{
  "source": {
    "index": "index_person"
  },
  "dest": {
    "index": "index_person_new"
  },
  "script": {
    "lang": "painless",
    "source": """
      if(ctx._source.age < 25){
        ctx._source.tag = '年輕人';
      }else{
        ctx._source.tag = '中年人';
      }
    """
  }
}

3.9.2 運(yùn)行結(jié)果

運(yùn)行結(jié)果

3.10 script query 查詢age<25

GET index_person/_search
{
  "query": {
    "script": {
      "script": {
        "lang": "painless",
        "source": """
          if(doc.age.size() == 0){
            return false;
          }
          return doc.age.value < 25;
        """
      }
    }
  }
}

3.11 script 聚合

GET index_person/_search
{
  "size": 0, 
  "aggs": {
    "agg_province": {
      "terms": {
        "script": {
          "lang": "painless",
          "source": """
            return doc.province
          """
        }, 
        "size": 10
      }
    },
    "agg_age":{
      "avg": {
        "script": "params._source.age"
      }
    }
  }
}

4、painless腳本調(diào)試

painless腳本調(diào)試

可以通過Debug.explain來進(jìn)行一些簡(jiǎn)單的調(diào)試。

5、腳本中的doc[..]和params._source[..]

doc[..]:使用doc關(guān)鍵字,將導(dǎo)致該字段的術(shù)語被加載到內(nèi)存(緩存),這將導(dǎo)致更快的執(zhí)行,但更多的內(nèi)存消耗。此外,doc[…]表示法只允許簡(jiǎn)單的值字段(您不能從中返回json對(duì)象),并且僅對(duì)非分析或基于單個(gè)術(shù)語的字段有意義。然而,如果可能的話,使用doc仍然是訪問文檔值的推薦方法。
params[_source][..]: 每次使用_source都必須加載和解析, 因此使用_source會(huì)相對(duì)而言要慢點(diǎn)。

腳本中的doc[..]和params._source[..]

6、painless腳本中的上下文

painless腳本中的上下文

詳細(xì)了解,請(qǐng)參考這個(gè)文檔https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-contexts.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容