2.X/6. Modeling Your Data

6-2-3. Sorting by Nested Fields

drscg 2017. 9. 23. 15:08

It is possible to sort by the value of a nested field, even though the value exists in a separate nested document. To make the result more interesting, we will add another record:

값은 개별 nested document에 있지만, nested field의 값으로 정렬하는 것은 가능하다. 더 흥미로운 결과를 만들어내기 위하여, 또 다른 document를 추가해 보자.

PUT /my_index/blogpost/2
{
  "title": "Investment secrets",
  "body":  "What they don't tell you ...",
  "tags":  [ "shares", "equities" ],
  "comments": [
    {
      "name":    "Mary Brown",
      "comment": "Lies, lies, lies",
      "age":     42,
      "stars":   1,
      "date":    "2014-10-18"
    },
    {
      "name":    "John Smith",
      "comment": "You're making it up!",
      "age":     28,
      "stars":   2,
      "date":    "2014-10-16"
    }
  ]
}

Imagine that we want to retrieve blog posts that received comments in October, ordered by the lowest number of stars that each blog post received. The search request would look like this:

각 블로그 게시물이 받은 stars 의 가장 작은 수부터 정렬하여, 10월에 댓글이 달린, 블로그 게시물을 검색한다고 가정해 보자. 검색 request는 아래와 유사할 것이다.

GET /_search
{
  "query": {
    "nested": { 
      "path": "comments",
      "filter": {
        "range": {
          "comments.date": {
            "gte": "2014-10-01",
            "lt":  "2014-11-01"
          }
        }
      }
    }
  },
  "sort": {
    "comments.stars": { 
      "order": "asc",   
      "mode":  "min",   
      "nested_filter": { 
        "range": {
          "comments.date": {
            "gte": "2014-10-01",
            "lt":  "2014-11-01"
          }
        }
      }
    }
  }
}

nested query는, 10월에 댓글이 달린 블로그 게시물로, 결과를 제한한다.

  

결과는 일치하는 댓글에서, comment.stars field를 기준으로, 가장 적은 값(min)부터, 오름차순(asc)로 정렬된다.

sort 절에서 nested_filter 는 주 query 절의 nested query와 동일하다. 이유는 다음과 같다.

Why do we need to repeat the query conditions in the nested_filter? The reason is that sorting happens after the query has been executed. The query matches blog posts that received comments in October, but it returns blog post documents as the result. If we didn’t include the nested_filterclause, we would end up sorting based on any comments that the blog post has ever received, not just those received in October.

nested_filter 에 query 조건을 반복해야 하는 이유가 무엇일까? 그 이유는 정렬은 query가 실행된 이후에 일어나기 때문이다. query는 10월에 댓글이 달린, 블로그 게시물과 일치한다. 하지만, 블로그 게시물 document를 결과로 반환한다. nested filter 절을 포함하지 않으면, 10월에 댓글이 달린 것이 아닌, 댓글이 달린 블로그 게시물의 모든 댓글을 기준으로, 정렬하게 될 것이다.

'2.X > 6. Modeling Your Data' 카테고리의 다른 글

6-2-1. Nested Object Mapping  (0) 2017.09.23
6-2-2. Querying a Nested Object  (0) 2017.09.23
6-2-4. Nested Aggregations  (0) 2017.09.23
6-3. Parent-Child Relationship  (0) 2017.09.23
6-3-1. Parent-Child Mapping  (0) 2017.09.23