Tech 기록지/Elastic Stack
[ElasticStack-21] _msearch on elasticsearch
Lio Grande
2020. 6. 23. 10:11
서로 다른 두 인덱스를 검색하는 쿼리가 다음과 같다고 하자.
(참조: https://mingsigi.tistory.com/entry/ElasticStack-16-Terms-query-Aggregation-sum-avg)
GET index_A/_search
{
"query": {
"terms": {
"subject": [
"국어",
"영어",
"수학"
]
}
},
"aggs": {
"aggregation_naming_1": {
"filter": {
"term": {
"file_name": "VALUE"
}
},
"aggs": {
"aggregation_naming_2": {
"sum": {
"script": "doc.score.value"
}
}
}
}
}
}
GET index_B/_search
{
"query": {
"match": {
"query": "이번 학기 국,영,수 점수는?",
"fuzziness": "AUTO"
}
}
}
두 인덱스의 쿼리를 동시에 처리하고 싶을때 사용하는 것이 multi search query (_msearch) 이다.
기본형태는 다음과 같다. (참조: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html)
GET index_A/_msearch
{}
{"query": {"ABOVE EXAMPLE QUERY of index_A"}}}
{}
{"index": "index_B"}
{"query": {"ABOVE EXAMPLE QUERY of index_B"}}}
_msearch 쿼리는 script를 활용하여 사용하는 것도 가능하다.
## my_template_1 생성
POST /_scripts/my_template_1
{
"script": {
"lang": "mustache",
"source": {
"query": {
"terms": {
"subject": [
"{{terms_value_1}}",
"{{terms_value_2}}",
"{{terms_value_3}}"
]
}
},
"aggs": {
"aggregation_naming_1": {
"filter": {
"term": {
"field": "file_name"
}
},
"aggs": {
"aggregation_naming_2": {
"sum": {
"script": "{{score_script}}"
}
}
}
}
}
}
}
}
## index_B 생성
GET index_B/_search
{
"query": {
"match": {
"query": "{{query_string}}",
"fuzziness": "AUTO"
}
}
}
GET _msearch/template
{"index": "index_A"}
{"id": "my_template_1", "params": {"terms_value_1": "국어", "terms_value_2": "영어", "terms_value_3": "수학", "score_script": "doc.score.value"}}
{"index": "index_B"}
{"id": "my_template_1", "params": {"query_string": "국어, 영어, 수학 점수와 합계는 몇이니?"}}