private static IReadOnlyCollection <HighlightOffset> ToHighlightOffsets( this HighlightHit highlightHit, string preAndPostTag) { // Validate parameters. if (string.IsNullOrWhiteSpace(preAndPostTag)) { throw new ArgumentNullException(nameof(preAndPostTag)); } // If null, return null. if (highlightHit == null) { return(null); } // Get the single string, as fragments should have been reduced to 0. string highlight = highlightHit.Highlights.Single(); // Enumerates offsets. IEnumerable <HighlightOffset> EnumerateHighlightHits() { // Need to parse. Split. var parts = highlight.Split(new [] { preAndPostTag }, StringSplitOptions.None); // The current offset. int offset = 0; // In a highlight? bool inHighlight = false; // Cycle through the parts. foreach (string part in parts) { // If in a highlight yield hit. if (inHighlight) { // Yield. yield return(new HighlightOffset { Offset = offset, Length = part.Length }); } // Increment the offset by the length. offset += part.Length; // Update whether or not in the highlight. inHighlight = !inHighlight; } } // Materialize the set. return(EnumerateHighlightHits().ToReadOnlyCollection()); }
public MagnetLinkSearchResultViewModel MagnetLinkSearch(string key, int pageIndex, int pageSize = 10) { var result = new MagnetLinkSearchResultViewModel() { SearchId = Guid.NewGuid().ToString(), SearchKey = key, PageIndex = pageIndex, PageSize = pageSize }; var response = _client.Search <MagnetLink>(s => s .Index(IndexName) .Type(TypeName) .From((pageIndex - 1) * pageSize) .Size(pageSize) //.Query(q => q. // MultiMatch(mm => mm.Fields(fs => fs.Fields(f => f.Name, f => f.InfoHash)).Query(key) // )) //.Query(q => q. // Match(m => m.Field(f => f.Name).Query(key) //)) //.Query(q => q // .MatchAll() //) .Query(q => q .Bool(b => b .Should(sd => sd .Term(t => t.Field(f => f.InfoHash).Value(key)), sd => sd .Match(m => m .Field(f => f.Name) .Query(key) ) ))) .Highlight(h => h //.PreTags("<em>") //.PostTags("</em>") .Fields( fs => fs.Field(f => f.Name) ) ) //.Sort(st => st.Descending(d => d.CreateTime)) .Source(sc => sc.IncludeAll()) ); result.Totals = (int)response.Total; result.FindTime = response.Took.ToString();//毫秒 foreach (var hit in response.Hits) { var item = hit.Source; //高亮 var highlightValue = new HighlightHit(); if (hit.Highlights.TryGetValue("name", out highlightValue)) { item.Name = highlightValue.Highlights.FirstOrDefault() ?? item.Name; } result.SearchResult.Add(item); } return(result); }