csharp 使用Umbraco Examine API搜索多个术语。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 使用Umbraco Examine API搜索多个术语。相关的知识,希望对你有一定的参考价值。

// This seems way too difficult for what you would expect to be a pretty common task;
// taking a search string from the user and finding documents which contain some or all of the terms 
// in the search string.

// This function naively splits a search string into terms and finds documents 
// which contain some or all of the terms. Does not handle quoted terms as or ignore case as it should.
public IEnumerable<SearchResult> Search(string searchString, string[] fields)
{
    // Spit the search string and return an empty list if no search string was provided.
    if (string.IsNullOrEmpty(searchString)) return new List<SearchResult>();
    string[] terms = searchString.Split(' ');

    // For the GroupOr function we need two lists: 
    //    1) The first containing fields to search 
    //    2) The second with search terms to find in the field at the same index in the first list
    
    // So.. if we have more than one search term we need to add every combination of search term and 
    // field to the lists.
    
    // Eg. If we have two fields and two search terms our list should look like this
    // searchFields = [Field1, Field2, Field1, Field2] 
    // searchTerms = [Term1, Term1, Term2, Term2]        
    
    var searchFields = new List<string>();
    var searchTerms = new List<string>();
    
    foreach(var t in terms) {
        searchTerms.AddRange(fields.Select(_ => t));
        searchFields.AddRange(fields);
    }
    
    // Pass our lists to GroupOr, compile and execute the search. 
    var query = ExamineManager.Instance.CreateSearchCriteria().GroupedOr(searchFields, searchTerms.ToArray());
    var search =  ExamineManager.Instance.Search(query.Compile());

    // Map the results into a basic search result stucture
    var results = search.Select(m => new SearchResult()
    {
        Title = m.Fields["nodeName"],
        NodeId = m.Id,
        Url = umbraco.library.NiceUrl(m.Id),
        Score = m.Score,
        DateUpdated = DateTime.Parse(m.Fields["updateDate"]).ToString("dd MMM, yyy")
    });   
    
    // Filtering and maybe paging if required.
    return results.Where(m => !string.IsNullOrEmpty(m.Url));
}

以上是关于csharp 使用Umbraco Examine API搜索多个术语。的主要内容,如果未能解决你的问题,请参考以下文章

csharp 与Umbraco ContentService一起使用的嵌套内容项的模型

csharp 一个Umbraco启动课程

csharp 用于嘲弄的Umbraco测试容器

csharp Umbraco获得所有重复的媒体

csharp 一堆Umbraco Membership API片段

csharp Umbraco IPublishedContent的一些有用的扩展方法。