Search code examples
c#azure-cognitive-search

Azure cognitive search wildcard filter


I've got an Azure search index with a complex type called "ArticleNames". This has two subfields: firstName and lastName. I'm trying to create a wildcard query across these fields, but having issues getting the syntax correct. If I look for an exact match, things work fine as follows:

        string facetFilter = " ArticleNames/any(person: person/lastName eq 'Trudeau')";
        var options = new SearchOptions()
        {
            Filter = facetFilter,
            Size = 10,
            IncludeTotalCount = true,
            SearchMode = SearchMode.All,
            Skip = start,
            QueryType = SearchQueryType.Full
        };
        SearchResults<SearchDocument> response = searchClient.Search<SearchDocument>("*", options)

How can I modify this so I'm able to get results for both Trudea and Truman if I pass in just 'Tru'?

Tks


Solution

  • For partial matches, you need to use full-text search, not filters. Assuming that ArticleNames/lastName is searchable, you should be able to use a prefix query like this:

    var options = new SearchOptions()
    {
        Size = 10,
        IncludeTotalCount = true,
        SearchMode = SearchMode.All,
        Skip = start,
        QueryType = SearchQueryType.Full
    };
    SearchResults<SearchDocument> response = searchClient.Search<SearchDocument>("ArticleNames/lastName:Tru*", options);
    

    Although it wasn't in your example, you mentioned in your question that you want to be able to query across firstName and lastName. I assume this means you'd want to be able to match any document where, for example, there is at least one article name where firstName starts with "Jo" AND lastName starts with "Sm" for a given article. You should be aware that this isn't possible today unless you're using strict filtering (e.g. firstName exactly equals "John" and lastName equals "Smith"). Only "uncorrelated" semantics are supported in full-text search queries across complex collections, as described in this article.

    For example, if you executed this search query:

    search=ArticleNames/firstName:Jo* AND ArticleNames/lastName:Sm*
    

    The AND refers to the document as a whole, not a given element of the ArticleNames field, so it would match a document with the names "Jonathan Brown" and "Alice Smart" even if your intent was to only match something like "Jonathan Smart".

    If this scenario is important to you, please vote on this User Voice item to help us prioritize it.