Search code examples
c#.netopensearch

OpenSearch.Client sort by filtered nested documents


I am trying to sort documents based on filtered nested documents, using the OpenSearch.Client, exactly as in this question for ElasticSearch: NEST elastic sort by filtered nested documents

However, the options OpenSearch.Client provides appear different, and it appears that there is no option for filtering nested objects at all.

My sorting requirements are these:


    "sort": [
        {
            "copies.creationDate": {
                "order": "desc",
                "nested" : {
                    "path" : "copies",
                    "filter" : {
                        "term" : {"copies.idOwnedByGroup" : 1}
                    }
                }
            }
        },
        {
            "idDocument": {
                "order": "desc"
            }
        }
    ],

And I have tried this :

.Sort(sort => {
    return sort.Field(d => d.Copies.First().CreationDate, SortOrder.Descending).Field(d => d.IdDocument, SortOrder.Descending)
}

And this:

.Sort(sort => {
    return sort.Descending(d => d.Copies.First().CreationDate).Descending(d => d.IdDocument);
}

But those methods contain no option to specify any nested object filtering. And I see no other methods to use.

From OpenSearch Dashboards it is possible though, using the JSON query above.

Am I missing something? Maybe this is not supported?


Solution

  • It turns out, this is similar to the NEST client, and I was just perplexed by the convoluted API:

    Func<NestedSortDescriptor<Document>, INestedSort> nestedSortDescriptor = n => n
            .Path(copiesNestedPath)
            .Filter(sff => sff
                .Term(tq => tq.Field(copyIdOwnedByGroupPath).Value(request.IdOrgGroup)) // Actual filtering.
             );
    
    return sort
       .Field(sf => sf
          .Field(d => d.Copies.First().CreationDate)
          .Order(SortOrder.Descending)
          .Nested(nestedSortDescriptor) // Required for fields inside nested objects.
        )
    

    And then one could add the 2nd field as well.

    Important note: You might need to specify a VERY LARGE value (larger than the numer of indexed documents) with .TrackTotalHits() otherwise the sort seems to not return the expected results.