Script 쿼리
Script 쿼리
Painless 스크립트 언어로 작성한 사용자 지정 조건에 따라 문서를 필터링하려면 script 쿼리를 사용해요. 이 쿼리는 스크립트가 true로 평가되는 문서를 반환해서, 표준 쿼리로는 표현할 수 없는 고급 필터링 로직을 가능하게 해요.
출처: 문서
본문
Painless 스크립트 언어로 작성한 사용자 지정 조건에 따라 문서를 필터링하려면 script 쿼리를 사용해요. 이 쿼리는 스크립트가 true로 평가되는 문서를 반환해, 표준 쿼리로는 표현할 수 없는 고급 필터링 로직을 가능하게 해요. 자세한 내용은 Painless scripting language를 참고하세요. script 쿼리는 계산 비용이 높아 가급적 조금씩 사용해야 해요. 꼭 필요할 때만 사용하고 search.allow_expensive_queries가 활성화되어 있는지(기본값은 true) 확인하세요. 자세한 내용은 Expensive queries를 참고하세요.
예제 (Example)
products라는 인덱스를 다음 매핑으로 생성하세요:
PUT /products
{
"mappings": {
"properties": {
"title": { "type": "text" },
"price": { "type": "float" },
"rating": { "type": "float" }
}
}
}
다음 요청으로 예제 문서를 인덱싱하세요:
POST /products/_bulk
{ "index": { "_id": 1 } }
{ "title": "Wireless Earbuds", "price": 99.99, "rating": 4.5 }
{ "index": { "_id": 2 } }
{ "title": "Bluetooth Speaker", "price": 79.99, "rating": 4.8 }
{ "index": { "_id": 3 } }
{ "title": "Noise Cancelling Headphones", "price": 199.99, "rating": 4.7 }
기본 script 쿼리
rating이 4.6보다 높은 상품을 반환하세요:
POST /products/_search
{
"query": {
"script": {
"script": {
"source": "doc['rating'].value > 4.6"
}
}
}
}
반환된 hits에는 rating이 4.6보다 높은 문서만 포함돼요:
{
...
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "2",
"_score": 1,
"_source": {
"title": "Bluetooth Speaker",
"price": 79.99,
"rating": 4.8
}
},
{
"_index": "products",
"_id": "3",
"_score": 1,
"_source": {
"title": "Noise Cancelling Headphones",
"price": 199.99,
"rating": 4.7
}
}
]
}
}
파라미터 (Parameters)
script 쿼리는 다음 최상위 파라미터를 사용해요.
Parameter Required/Optional Description
script.source | 필수 | true 또는 false로 평가되는 스크립트 코드예요.
script.params | 선택 | 스크립트 안에서 참조하는 사용자 정의 파라미터예요.
스크립트 파라미터 사용
params를 사용해 값을 안전하게 주입할 수 있고, 스크립트 컴파일 캐싱의 이점도 누릴 수 있어요:
POST /products/_search
{
"query": {
"script": {
"script": {
"source": "doc['price'].value
반환된 hits에는 가격이 100 미만인 문서만 포함돼요:
{
...
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "1",
"_score": 1,
"_source": {
"title": "Wireless Earbuds",
"price": 99.99,
"rating": 4.5
}
},
{
"_index": "products",
"_id": "2",
"_score": 1,
"_source": {
"title": "Bluetooth Speaker",
"price": 79.99,
"rating": 4.8
}
}
]
}
}
여러 조건 결합
rating이 4.5보다 높고 가격이 100보다 낮은 상품을 검색하려면 다음 쿼리를 사용하세요:
POST /products/_search
{
"query": {
"script": {
"script": {
"source": "doc['rating'].value > 4.5 && doc['price'].value
요구 사항과 일치하는 문서만 반환돼요:
{
"took": 12,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "2",
"_score": 1,
"_source": {
"title": "Bluetooth Speaker",
"price": 79.99,
"rating": 4.8
}
}
]
}
}