Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PlainElastic.Net facet query builder sample
using System;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
using PlainElastic.Net.Utils;
namespace FacetQuerySample
{
class Item
{
public int Id { get; set; }
public bool Active { get; set; }
public string Name { get; set; }
public int Category { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
class Criterion
{
public string FullText { get; set; }
}
class Program
{
static void Main(string[] args)
{
var connection = new ElasticConnection("localhost", 9200);
var serializer = new JsonNetSerializer();
// Add sample item document to http://localhost:9200/store/item/ index.
var addedItem = new Item
{
Id = 2,
Active = true,
Name = "Query Item",
Category = 10,
Description = "Item description text",
Price = 200
};
string itemJson = serializer.Serialize(addedItem);
connection.Put(Commands.Index("store", "item", id: addedItem.Id.AsString()).Refresh(), itemJson);
// Build faceted query with FullText criterion defined.
string query = BuildFacetQuery(new Criterion { FullText = "text" });
string result = connection.Post(Commands.Search("store", "item"), query);
// Parse facets query result
var searchResults = serializer.ToSearchResult<Item>(result);
var itemsPerCategoryTerms = searchResults.facets.Facet<TermsFacetResult>("ItemsPerCategoryCount").terms;
foreach (var facetTerm in itemsPerCategoryTerms)
{
Console.WriteLine("Category: {0} Items Count: {1}".F(facetTerm.term, facetTerm.count));
}
Console.ReadKey();
}
public static string BuildFacetQuery(Criterion criterion)
{
return new QueryBuilder<Item>()
.Query(q => q
.QueryString(qs => qs
.Fields(item => item.Name, item => item.Description)
.Query(criterion.FullText)
)
)
// Facets Part
.Facets(facets => facets
.Terms(t => t
.FacetName("ItemsPerCategoryCount")
.Field(item => item.Category)
.Size(100)
)
)
.BuildBeautified();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment