Skip to content

Commit

Permalink
feat: added withHighlight to GetSearchRequest
Browse files Browse the repository at this point in the history
Refs: SITKO-CORE-T-24
  • Loading branch information
IgorAlymov committed Aug 8, 2024
1 parent cd28c45 commit 55e6e68
Showing 1 changed file with 17 additions and 21 deletions.
38 changes: 17 additions & 21 deletions src/Sitko.Core.Search.OpenSearch/OpenSearchSearcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,29 +104,22 @@ public async Task<TSearchModel[]> SearchAsync(string indexName, string term, int
{
indexName = $"{Options.Prefix}_{indexName}";
var searchResponse = await GetClient()
.SearchAsync<TSearchModel>(x => GetSearchRequest(x, indexName, term, searchType, limit), cancellationToken);
.SearchAsync<TSearchModel>(x => GetSearchRequest(x, indexName, term, searchType, limit, withHighlight),
cancellationToken);
if (searchResponse.ServerError != null)
{
logger.LogError("Error while searching in {IndexName}: {ErrorText}", indexName, searchResponse.ServerError);
}

var result = searchResponse.Hits.Select(h =>
new TSearchModel
{
var searchModel = new TSearchModel
{
Id = h.Source.Id,
Content = h.Source.Content,
Date = h.Source.Date,
Title = h.Source.Title,
Url = h.Source.Url
};
if (withHighlight)
{
searchModel.Highlight = h.Highlight;
}
return searchModel;
Id = h.Source.Id,
Content = h.Source.Content,
Date = h.Source.Date,
Title = h.Source.Title,
Url = h.Source.Url,
Highlight = h.Highlight
}
).ToArray();
return result;
Expand Down Expand Up @@ -261,7 +254,7 @@ private static string GetSearchText(string? term)
}

private SearchDescriptor<TSearchModel> GetSearchRequest(SearchDescriptor<TSearchModel> descriptor,
string indexName, string term, SearchType searchType, int limit = 0)
string indexName, string term, SearchType searchType, int limit = 0, bool withHighlight = false)
{
var names = GetSearchText(term);
switch (searchType)
Expand All @@ -279,13 +272,16 @@ private SearchDescriptor<TSearchModel> GetSearchRequest(SearchDescriptor<TSearch
break;
}

return descriptor
.Highlight(h =>
if (withHighlight)
{
descriptor.Highlight(h =>
h.Fields(fs => fs
.Field(p => p.Title)
.PreTags(Options.PreTags)
.PostTags(Options.PostTags))
)
.PostTags(Options.PostTags)));
}

return descriptor
.Sort(s => s.Descending(SortSpecialField.Score).Descending(model => model.Date))
.Size(limit > 0 ? limit : 20)
.Index(indexName.ToLowerInvariant());
Expand Down

0 comments on commit 55e6e68

Please sign in to comment.