Created
July 11, 2012 22:02
-
-
Save Yegoroff/3093936 to your computer and use it in GitHub Desktop.
PlainElastic.Net facet query builder sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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