# Filter or sort hits to get one with special flag

**URL:** <https://discuss.elastic.co/t/filter-or-sort-hits-to-get-one-with-special-flag/136300>\
**Category:** Elasticsearch\
**Created:** [June 18, 2018, 11:44am UTC](https://discuss.elastic.co/t/filter-or-sort-hits-to-get-one-with-special-flag/136300 "2018-06-18T11:44:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ov7a](https://avatars.discourse-cdn.com/v4/letter/o/ecae2f/32.png) [@ov7a](https://discuss.elastic.co/u/ov7a)\
**Post date:** [June 18, 2018, 11:44am UTC](https://discuss.elastic.co/t/filter-or-sort-hits-to-get-one-with-special-flag/136300/1 "2018-06-18T11:44:38Z")

</div>

I have a query like this.

```
{
  "size" : 0,
  "query" : {
    "constant_score" : {
      "filter" : {
        "bool" : {
          "must" : [
            {
              "term" : {
                "field1" : {
                  "value" : "value1",
                  "boost" : 1.0
                }
              }
            },
            {
            	//... some other filters
            }
          ]
        }
      },
      "boost" : 1.0
    }
  },
  "aggregations" : {
    "field2-agg" : {
      "sum" : {
        "field" : "field2"
      }
    }
  }
}

```

I want to also obtain single element with `field3 = true`.  
One way to do this is to make a bulk request with 2 requests: this and a copy of this with additional `must` closure and size 1. But this would result in executing the same query twice.  
Another way is to add a `top_hits` aggregation with custom sorting by field4. But sorting is expensive.

Which variant would be executed faster? Is there more elegant way to do this?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 16, 2018, 11:44am UTC](https://discuss.elastic.co/t/filter-or-sort-hits-to-get-one-with-special-flag/136300/2 "2018-07-16T11:44:38Z")

</div>

Closed on July 16, 2018, 11:44am UTC

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
