# Sorting collapsed results based on nested documents

**URL:** <https://discuss.elastic.co/t/sorting-collapsed-results-based-on-nested-documents/318480>\
**Category:** Elasticsearch\
**Created:** [November 8, 2022, 10:20pm UTC](https://discuss.elastic.co/t/sorting-collapsed-results-based-on-nested-documents/318480 "2022-11-08T22:20:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tombrisland](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tombrisland/32/78133_2.png) [@tombrisland](https://discuss.elastic.co/u/tombrisland)\
**Post date:** [November 8, 2022, 10:20pm UTC](https://discuss.elastic.co/t/sorting-collapsed-results-based-on-nested-documents/318480/1 "2022-11-08T22:20:10Z")

</div>

I have a query which makes use of collapse to de-duplicate results. I'm expecting some collapsed results to have multiple duplicates, and some to be unique. I would like to sort the entries in such a way that the results with the most duplicates come first.

I was expecting something like a `score_mode` parameter similar to [nested queries](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html#nested-top-level-params), which would cause the nested documents to affect the score of the collapsed bucket - but that doesn't exist at the moment.

_Simplified Example_

Suppose I have two indexes - one containing song metadata, and one containing song lyrics. I want to query over both at the same time to find songs based on fields on both documents.

The query might look like this:

```auto
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "artist": "johnny"
          }
        },
        {
          "terms": {
            "lyrics": [
              "the",
              "cat"
            ]
          }
        }
      ]
    }
  },
  "collapse": {
    "field": "song"
  }
}

```

I would want to sort results which hit both should clauses to the top of the results, but I can't see a way to do this.

I think the standard advice would be to merge the documents, but unfortunately in my actual use-case the song-lyrics index is populated by a task which takes a long time to run. In the meantime I want the metadata to be available to query, and updating a single document once the result is in causes major issues with the cluster performance.

Does anyone know of a way to accomplish this without merging the documents together?

---

<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:** [December 6, 2022, 10:20pm UTC](https://discuss.elastic.co/t/sorting-collapsed-results-based-on-nested-documents/318480/2 "2022-12-06T22:20:48Z")

</div>

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