How to search based on field in azure search?

2019-09-15 18:49发布

i am using a azure search, and i have a console app with the code as below, which is working fine.

        DocumentSearchResult<Hotel> results;
        Console.WriteLine("Search started\n"); 
        results = indexClient.Documents.Search<Hotel>("smart", new SearchParameters { Top=5 });
        WriteDocuments(results);

currently its searching a text with word "smart". this is straight forword, what i need is i have several fields in the table, i want to search based on the feild .

for example let i have two fields 1)Title 2)SoldDate

I have to write code for finding items which has title 'john' and which has a sold date < current date.

what should i do to achieve this?

1条回答
迷人小祖宗
2楼-- · 2019-09-15 19:30

You can achieve what you want with search and a filter:

// Approach #1
string currentDate = DateTime.UtcNow.ToString("O");
var parameters = new SearchParameters()
{
    Filter = "soldDate lt " + currentDate,
    Top = 5
}

results = indexClient.Documents.Search<Hotel>("john", parameters);

This will filter the documents to only those with a soldDate before currentDate, and then searches the filtered documents such that documents match if any of the searchable fields contain "john". You can narrow this down to just the title field like this:

// Approach #2
string currentDate = DateTime.UtcNow.ToString("O");
var parameters = new SearchParameters()
{
    Filter = "soldDate lt " + currentDate,
    SearchFields = new[] { "title" },
    Top = 5
}

results = indexClient.Documents.Search<Hotel>("john", parameters);

Or like this:

// Approach #3
string currentDate = DateTime.UtcNow.ToString("O");
var parameters = new SearchParameters()
{
    Filter = "soldDate lt " + currentDate,
    QueryType = QueryType.Full,
    Top = 5
}

results = indexClient.Documents.Search<Hotel>("title:john", parameters);

Which way you use depends on whether you want all search terms to be limited to a specific set of fields (Approach #2), or if you want specific terms to match specific fields (Approach #3).

The reference for SearchParameters is on docs.microsoft.com.

查看更多
登录 后发表回答