Search code examples
c#azureazure-cognitive-searchazure-search-.net-sdk

Ordering by complex types in Azure Search .NET SDK?


So I have an index built with a parent/child structure like follows:

    {
            "Id": "13704",
            "StreetNumber": "29",
            "StreetName": "Fiction Road",
            "PostalCode": "DD1 G33"
            "CityName": "Fiction City",
            "Property": {
                "ID": 13592,
                "ParentPropertyID": 123
            }
    }

I want to order by Property/ParentPropertyID, which works fine on the Azure Portal using the following query string:

search=DD1 G33&searchmode=all&$orderby=Property/ParentPropertyID asc

This works as expected, and returns me a list of records matching this postcode ordered as specified. But, when I try to do this in C# with the Azure Search SDK, it returns results but doesn't seem to apply the order by. If I use one of the parent fields (e.g. StreetNumber) instead, it does work, so it seems limited to complex types. Code:

            SearchParameters parameters;
            DocumentSearchResult<TempAddress> results;

            parameters =
                new SearchParameters()
                {
                    SearchMode = SearchMode.All,
                    OrderBy = new[] { "Property/ParentPropertyID asc" }
                };

            results = _searchIndexClient.Documents.Search<TempAddress>("DD1 G33", parameters);

The results object returns the list of correct results, but the OrderBy hasn't been applied. It seems to find the field without any issues as it doesn't throw any errors. I can't really seem to find any examples of ordering by complex types either, or any examples involving complex types is using the same syntax as I've used above (i.e. ParentProp/ChildProp). If I change

OrderBy = new[] { "Property/ParentPropertyID asc" }

to:

OrderBy = new[] { "StreetNumber desc" }

The OrderBy works with no problems. I can't really see why this isn't working in code, but works on the portal?


Solution

  • Thanks to sathya_vijayakumar-MSFT I've figured out what the problem was, posting an answer in case anyone else has the same issue. I was using the Microsoft.Azure.Search Nuget package, which only goes up to version 10, but version 10 targets the 2019-05-06 Search API which doesn't seem to support ordering by complex types. If I manually make a query myself using the 2020-06-30 API, it works fine. The same manual query using the 2019-05-06 version doesn't work!

    It turns out version 11 of the SDK is available targetting this API version, but it's under a different NuGet package: Azure.Search.Documents which is a fair breaking change from the original package (see https://learn.microsoft.com/en-us/azure/search/search-dotnet-sdk-migration-version-11).