Create or Update Stored Script API

Create or Update Stored Script API

1.0에서 도입

클러스터 상태에 저장된 스크립트(stored script)나 검색 템플릿을 만들거나 업데이트해요. 저장된 스크립트는 한 번 컴파일되고 여러 요청에서 재사용되어 더 나은 성능을 내요.

Painless 스크립팅에 대한 추가 정보는 다음을 참고해요.

출처: 문서

본문

경로 매개변수 (Path parameters)

매개변수 데이터 타입 설명
script-id String 저장된 스크립트 또는 검색 템플릿 ID예요. 클러스터 전체에서 고유해야 해요. 필수예요.

쿼리 매개변수 (Query parameters)

모든 매개변수는 선택 사항이에요.

매개변수 데이터 타입 설명
context String 스크립트 또는 검색 템플릿이 실행될 컨텍스트예요. 오류를 막기 위해 API가 이 컨텍스트에서 스크립트나 템플릿을 즉시 컴파일해요.
cluster_manager_timeout Time 클러스터 매니저에 연결되기를 기다리는 시간이에요. 기본값은 30초예요.
timeout Time 응답을 기다리는 시간이에요. 타임아웃 값 전에 응답을 받지 못하면 요청이 실패하고 오류를 반환해요. 기본값은 30초예요.

요청 본문 필드 (Request body fields)

필드 데이터 타입 설명
script Object 스크립트 또는 검색 템플릿과 그 매개변수, 언어를 정의해요. 아래 Script 객체 섹션을 참고해요.

Script 객체

필드 데이터 타입 설명
lang String 스크립팅 언어예요. 필수예요.
source String 또는 Object 필수예요.

스크립트의 경우 스크립트 내용을 담은 문자열이에요.

검색 템플릿의 경우 검색 템플릿을 정의하는 객체예요. Search API 요청 본문과 같은 매개변수를 지원해요. 검색 템플릿은 Mustache 변수도 지원해요.

예시 요청 (Example request)

다음 예시 요청은 다음 문서들이 들어 있는 books 인덱스를 사용해요.

POST /_bulk
{"index":{"_index":"books","_id":1}}
{"name":"book1","author":"Faustine","ratings":[4,3,5]}
{"index":{"_index":"books","_id":2}}
{"name":"book2","author":"Amit","ratings":[5,5,5]}
{"index":{"_index":"books","_id":3}}
{"name":"book3","author":"Gilroy","ratings":[2,1,5]}

Python 클라이언트로는 이렇게 호출해요:

response = client.bulk(
body = '''
{"index":{"_index":"books","_id":1}}
{"name":"book1","author":"Faustine","ratings":[4,3,5]}
{"index":{"_index":"books","_id":2}}
{"name":"book2","author":"Amit","ratings":[5,5,5]}
{"index":{"_index":"books","_id":3}}
{"name":"book3","author":"Gilroy","ratings":[2,1,5]}
'''
)

Painless 스크립트 만들기 (Creating a Painless script)

다음 요청은 Painless 스크립트 my-first-script를 만들어요. 각 책의 평점을 합산해서 그 합을 출력에 보여줘요.

PUT /_scripts/my-first-script
{
"script": {
"lang": "painless",
"source": """
int total = 0;
for (int i = 0; i < doc['ratings'].length; ++i) {
total += doc['ratings'][i];
}
return total;
"""
}
}

Python 클라이언트로는 이렇게 호출해요:

response = client.put_script(
id = "my-first-script",
body = '''
{
"script": {
"lang": "painless",
"source": """
int total = 0;
for (int i = 0; i < doc['ratings'].length; ++i) {
total += doc['ratings'][i];
}
return total;
"""
}
}
'''
)

앞선 예시는 OpenSearch Dashboards의 Dev Tools 콘솔 구문을 사용한 거예요. cURL 요청으로도 할 수 있어요.

다음 cURL 요청은 앞선 Dashboards 콘솔 예시와 동일해요:

curl -XPUT "http://opensearch:9200/_scripts/my-first-script" -H 'Content-Type: application/json' -d'
{
"script": {
"lang": "painless",
"source": "\n          int total = 0;\n          for (int i = 0; i < doc['\''ratings'\''].length; ++i) {\n            total += doc['\''ratings'\''][i];\n          }\n          return total;\n        "
}
}'

스크립트 실행에 대한 내용은 Execute Painless stored script를 참고해요.

매개변수가 있는 저장된 스크립트 만들기·업데이트하기 (Creating or updating a stored script with parameters)

Painless 스크립트는 params를 지원해서 스크립트에 변수를 전달할 수 있어요.

다음 요청은 Painless 스크립트 multiplier-script를 만들어요. 각 책의 평점을 합산하고, 합산 값을 multiplier 매개변수로 곱한 결과를 출력에 보여줘요:

PUT /_scripts/multiplier-script
{
"script": {
"lang": "painless",
"source": """
int total = 0;
for (int i = 0; i < doc['ratings'].length; ++i) {
total += doc['ratings'][i];
}
return total * params['multiplier'];
"""
}
}

Python 클라이언트로는 이렇게 호출해요:

response = client.put_script(
id = "multiplier-script",
body = '''
{
"script": {
"lang": "painless",
"source": """
int total = 0;
for (int i = 0; i < doc['ratings'].length; ++i) {
total += doc['ratings'][i];
}
return total * params['multiplier'];
"""
}
}
'''
)

예시 응답 (Example response)

PUT _scripts/my-first-script 요청은 다음 필드를 반환해요:

{
"acknowledged" : true
}

스크립트가 제대로 만들어졌는지 확인하려면 Get stored script API에 script 경로 매개변수로 스크립트 이름을 넘겨 확인해요.

필요한 권한 (Required permissions)

Security 플러그인을 사용한다면 적절한 권한이 있는지 확인해야 해요: cluster:admin/script/put.

더 알아보기