Skip to content

Instantly share code, notes, and snippets.

@Yegoroff
Created January 14, 2014 19:57
Show Gist options
  • Save Yegoroff/8424594 to your computer and use it in GitHub Desktop.
Save Yegoroff/8424594 to your computer and use it in GitHub Desktop.
Date Histogram Facet sample
using System;
using System.Linq;
using PlainElastic.Net;
using PlainElastic.Net.Mappings;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
using PlainElastic.Net.Utils;
namespace RandomSortSample
{
internal class Tweet
{
public string Name { get; set; }
public string Text { get; set; }
public DateTime Date { get; set; }
}
class Program
{
static void Main(string[] args)
{
var connection = new ElasticConnection("localhost");
var serializer = new JsonNetSerializer();
// cleanup previous run data and mappings
connection.Delete(Commands.Delete("twitter").Refresh());
connection.Post(Commands.CreateIndex("twitter"));
// map Tweet.Date property as 'date' in ElasticSearch
var tweetMap = new MapBuilder<Tweet>()
.RootObject("tweet", r => r
.Properties(p => p
.Date(tweet => tweet.Date)
)
).Build();
connection.Put(Commands.PutMapping("twitter", "tweet"), tweetMap);
// add sample tweets
for (int i = 1; i < 12; i++)
{
var tweet = new Tweet
{
Name = "User" + i,
Text = "some text from user" + i,
Date = new DateTime(2014, 1, i)
};
connection.Put(Commands.Index("twitter", "tweet", i.AsString()).Refresh(),
serializer.Serialize(tweet));
}
// build DateHistogramFacet query for 5 days interval.
var query = new QueryBuilder<Tweet>()
.Query(q => q
.MatchAll()
)
.Facets(fc => fc
.DateHistogram(dh => dh
.FacetName("tweetHistogram")
.Field(tweet => tweet.Date)
.Interval("5d")
)
)
.BuildBeautified();
var result = connection.Post(Commands.Search("twitter", "tweet"), query);
// deserialize histogram entries
var typedResults = serializer.Deserialize<SearchResult<Tweet>>(result);
var histogramEntries = typedResults.facets["tweetHistogram"].As<DateHistogramFacetResult>().entries;
Console.WriteLine(histogramEntries.Select(entry => "time: " + entry.time + " UTC Time:" + entry.UtcTime() +" count:" + entry.count).JoinWithSeparator("\r\n"));
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment