Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch.NET NEST Object Initializer syntax for a highlight request

I've got:

        var result = _client.Search<ElasticFilm>(new SearchRequest("blaindex", "blatype")
        {
            From = 0,
            Size = 100,
            Query = titleQuery || pdfQuery,
            Source = new SourceFilter
            {
                Include = new []
                {
                    Property.Path<ElasticFilm>(p => p.Url),
                    Property.Path<ElasticFilm>(p => p.Title),
                    Property.Path<ElasticFilm>(p => p.Language),
                    Property.Path<ElasticFilm>(p => p.Details),
                    Property.Path<ElasticFilm>(p => p.Id)
                }
            },
            Timeout = "20000"
        });

And I'm trying to add a highlighter filter but I'm not that familiar with the Object Initializer (OIS) C# syntax. I've checked NEST official pages and SO but can't seem to return any results for specifically the (OIS).

I can see the Highlight property in the Nest.SearchRequest class but I'm not experienced enough (I guess) to simply construct what I need from there - some examples and explanations as to how to employ a highlighter with OIS would be hot!

like image 294
notsoobvious Avatar asked May 25 '15 10:05

notsoobvious


1 Answers

This is the fluent syntax:

var response= client.Search<Document>(s => s
    .Query(q => q.Match(m => m.OnField(f => f.Name).Query("test")))
    .Highlight(h => h.OnFields(fields => fields.OnField(f => f.Name).PreTags("<tag>").PostTags("</tag>"))));

and this is by object initialization:

var searchRequest = new SearchRequest
{
    Query = new QueryContainer(new MatchQuery{Field = Property.Path<Document>(p => p.Name), Query = "test"}),
    Highlight = new HighlightRequest
    {
        Fields = new FluentDictionary<PropertyPathMarker, IHighlightField>
        {
            {
                Property.Path<Document>(p => p.Name),
                new HighlightField {PreTags = new List<string> {"<tag>"}, PostTags = new List<string> {"</tag>"}}
            }
        }
    }
};

var searchResponse = client.Search<Document>(searchRequest);

UPDATE

NEST 7.x syntax:

var searchQuery = new SearchRequest
{
    Highlight = new Highlight
    {
        Fields = new FluentDictionary<Field, IHighlightField>()
            .Add(Nest.Infer.Field<Document>(d => d.Name),
                new HighlightField {PreTags = new[] {"<tag>"}, PostTags = new[] {"<tag>"}})
    }
};

My document class:

public class Document
{
    public int Id { get; set; }
    public string Name { get; set; } 
}  
like image 182
Rob Avatar answered Oct 21 '22 12:10

Rob