Session: Querying: How to use Highlighting
Highlighting can be a great feature for increasing search UX. To take leverage of it use Highlight
method.
Syntax
IRavenQueryable<T> Highlight(
string fieldName,
int fragmentLength,
int fragmentCount,
out Highlightings highlightings);
IRavenQueryable<T> Highlight(
string fieldName,
int fragmentLength,
int fragmentCount,
HighlightingOptions options,
out Highlightings highlightings);
IRavenQueryable<T> Highlight(
Expression<Func<T, object>> path,
int fragmentLength,
int fragmentCount,
out Highlightings highlightings);
IRavenQueryable<T> Highlight(
Expression<Func<T, object>> path,
int fragmentLength,
int fragmentCount,
HighlightingOptions options,
out Highlightings highlightings);
Parameters | ||
---|---|---|
fieldName | string | Name of a field to highlight. |
path | Expression<Func<T, object>> |
Path to a field to highlight. |
fragmentLength | int | Maximum length of text fragments that will be returned. |
fragmentCount | int | Maximum number of fragments that will be returned. |
options | HighlightingOptions |
Options that can be used for customization. |
highlightings | Highlightings |
Instance of a Highlightings that contains the highlight fragments for each returned result. |
Options
public string GroupKey { get; set; }
public string[] PreTags { get; set; }
public string[] PostTags { get; set; }
Options | ||
---|---|---|
GroupKey | string | Grouping key for the results. If null results are grouped by document ID (default). |
PreTags | string[] |
Array of pre tags used when highlighting. |
PostTags | string[] |
Array of post tags used when highlighting. |
Example
List<SearchItem> results = session
.Query<SearchItem, ContentSearchIndex>()
.Highlight(x => x.Text, 128, 1, out Highlightings highlightings)
.Search(x => x.Text, "raven")
.ToList();
StringBuilder builder = new StringBuilder()
.AppendLine("<ul>");
foreach (SearchItem result in results)
{
string[] fragments = highlightings.GetFragments(result.Id);
builder.AppendLine($"<li>{fragments.First()}</li>");
}
string ul = builder
.AppendLine("</ul>")
.ToString();
List<SearchItem> results = await asyncSession
.Query<SearchItem, ContentSearchIndex>()
.Highlight(x => x.Text, 128, 1, out Highlightings highlightings)
.Search(x => x.Text, "raven")
.ToListAsync();
StringBuilder builder = new StringBuilder()
.AppendLine("<ul>");
foreach (SearchItem result in results)
{
string[] fragments = highlightings.GetFragments(result.Id);
builder.AppendLine($"<li>{fragments.First()}</li>");
}
string ul = builder
.AppendLine("</ul>")
.ToString();
from index 'ContentSearchIndex'
where search(Text, 'raven')
include highlight(Text, 128, 1)
Remarks
Note
Default <b></b>
tags are coloured and colours are returned in following order:
- yellow,
- lawngreen,
- aquamarine,
- magenta,
- palegreen,
- coral,
- wheat,
- khaki,
- lime,
- deepskyblue,
- deeppink,
- salmon,
- peachpuff,
- violet,
- mediumpurple,
- palegoldenrod,
- darkkhaki,
- springgreen,
- turquoise,
- powderblue