[ElasticStack-18] Result filtering of searching query
aggregation을 활용하여 특정 필드만 작업(sum, avg, ...)시 "query" 결과로 aggregation에 해당하는 조건의 결과값들만 보고 싶을 때 filtering search를 활용하자.
(Aggregation filtering 참고 : https://mingsigi.tistory.com/entry/ElasticStack-16-Terms-query-Aggregation-sum-avg)
위의 예시를 기준으로 "file_name" 필드에 값이 VALUE와 COMPLETE으로 구성되어 있다고 가정하자.
그러면 aggregation filter 수행 시 query에는 필터링을 걸어놓지 않았기 떄문에, "file_name"이 VALUE인 항목의 값들과 COMPLETE인 항목의 값들이 동시에 검색이 된다.
이때, VALUE 항목에 대한 query 검색 결과만을 보고 싶다면 다음과 같이 작성해보자.
GET index/_search
{
"query": {
"bool": {
"must": [
{
"terms": {
"subject": [
"국어",
"영어",
"수학"
]
}
}
],
"filter": [
{
"term": {
"file_name": "VALUE"
}
}
]
}
},
"aggs": {
... ## 나머지 부분은 Aggregation 항목 참조
}
}
쿼리의 결과로는 "file_name"이 VALUE인 항목들만 검색되고, 그에 관련한 합 등이 산출된다.
공식 API (filter context)
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html
Query and filter context | Elasticsearch Reference [7.7] | Elastic
Use query clauses in query context for conditions which should affect the score of matching documents (i.e. how well does the document match), and use all other query clauses in filter context.
www.elastic.co