Skip to content

Instantly share code, notes, and snippets.

@Yegoroff
Last active December 17, 2015 06:58
Show Gist options
  • Save Yegoroff/5569008 to your computer and use it in GitHub Desktop.
Save Yegoroff/5569008 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
namespace ConsoleApplication15
{
class Program
{
static void Main()
{
var connection = new ElasticConnection("localhost", 9200);
var serializer = new JsonNetSerializer();
// Add a sample document to index.
var note = new Note {Caption = "Test Note", Text = "Note to test highlighting"};
string noteJson = serializer.ToJson(note);
connection.Put(Commands.Index("notes", "note", "1"), noteJson);
// Create query with highlighting.
string query = new QueryBuilder<Note>()
.Query(q => q
.QueryString(qs => qs
.Fields(c => c.Caption)
.Query("Note")
)
)
.Highlight(h => h
.PreTags("<b>")
.PostTags("</b>")
.Fields(
f => f.FieldName(n => n.Caption).Order(HighlightOrder.score),
f => f.FieldName(n => n.Text)
)
)
.BuildBeautified();
Console.WriteLine("QUERY: \r\n" + query);
// Execute query and deserialize results.
string results = connection.Post(Commands.Search("notes", "note"), query);
var noteResults = serializer.ToSearchResult<Note>(results);
// Print first highlighted fragment for each hit.
Console.WriteLine("\r\nHIGHLIGHTED FRAGMENTS: \r\n");
foreach (var hit in noteResults.hits.hits)
{
foreach (var field in hit.highlight)
{
string fieldName = field.Key;
string[] fragments = field.Value;
Console.WriteLine(fieldName + ": " + fragments.FirstOrDefault());
}
}
Console.ReadKey();
}
}
public class Note
{
public string Caption { get; set; }
public string Text { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment