How to search based on field in azure search?

强颜欢笑 提交于 2019-12-12 02:32:52

问题


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:


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.



来源:https://stackoverflow.com/questions/43493372/how-to-search-based-on-field-in-azure-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!