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

How do I set the new BM25Similarity algorithm on indexes created via the C# Azure search API?


As per the new documenation, Azure are recommending you use the new BM25 similarity algorithm on newly created indexes in Azure search. See link here

https://learn.microsoft.com/en-us/azure/search/index-ranking-similarity

This is all very well for those who create the index manually via the Azure portal. But how do we add this via the C# azure search API? In the docs it shows a Json example

{
    "name": "indexName",
    "fields": [
        {
            "name": "id",
            "type": "Edm.String",
            "key": true
        },
        {
            "name": "name",
            "type": "Edm.String",
            "searchable": true,
            "analyzer": "en.lucene"
        },
        ...
    ],
    "similarity": {
        "@odata.type": "#Microsoft.Azure.Search.BM25Similarity"
    }
}

However, in the API there is no similarity object on the Index object? Any pointers of adding this would be appreciated. Especially as we can't update existing Indexes!!


Solution

  • The BM25Similarity class is now available in the new Azure.Search.Documents package. You can use it to create an index like so:

    SearchIndex index = new SearchIndex("hotels")
    {
        Fields =
        {
            new SimpleField("hotelId", SearchFieldDataType.String) { IsKey = true, IsFilterable = true, IsSortable = true },
            new SearchableField("hotelName") { IsFilterable = true, IsSortable = true },
            new SearchableField("description") { AnalyzerName = LexicalAnalyzerName.EnLucene },
            new SearchableField("tags", collection: true) { IsFilterable = true, IsFacetable = true },
            new ComplexField("address")
            {
                Fields =
                {
                    new SearchableField("streetAddress"),
                    new SearchableField("city") { IsFilterable = true, IsSortable = true, IsFacetable = true },
                    new SearchableField("stateProvince") { IsFilterable = true, IsSortable = true, IsFacetable = true },
                    new SearchableField("country") { IsFilterable = true, IsSortable = true, IsFacetable = true },
                    new SearchableField("postalCode") { IsFilterable = true, IsSortable = true, IsFacetable = true }
                }
            }
        },
        Similarity = new BM25Similarity(),
        Suggesters =
        {
            // Suggest query terms from the hotelName field.
            new SearchSuggester("sg", "hotelName")
        }
    };
    

    See our README for more information.