Skip to content

Instantly share code, notes, and snippets.

@Yegoroff
Created May 21, 2012 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yegoroff/2765335 to your computer and use it in GitHub Desktop.
Save Yegoroff/2765335 to your computer and use it in GitHub Desktop.
PlainElastic.Net condition-less query builder sample
using System;
using System.Linq;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
using PlainElastic.Net.Utils;
namespace PlainSample
{
class Program
{
class Item
{
public int Id { get; set; }
public bool Active { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
class Criterion
{
public string FullText { get; set; }
public double? MinPrice { get; set; }
public double? MaxPrice { get; set; }
public bool? Active { get; set; }
}
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 = 1,
Active = true,
Name = "Query Item",
Description = "Item description text",
Price = 100
};
string itemJson = serializer.Serialize(addedItem);
connection.Put(Commands.Index("store", "item", id: addedItem.Id.AsString()).Refresh(), itemJson);
// Build query with only FullText criterion defined.
string query = BuildQuery(new Criterion { FullText = "text" });
string result = connection.Post(Commands.Search("store", "item"), query);
Item foundItem = serializer.ToSearchResult<Item>(result).Documents.First();
Console.WriteLine("Name: " + foundItem.Name);
Console.WriteLine("Alias: " + foundItem.Description);
Console.WriteLine("Query: " + query);
Console.WriteLine("JSON result: " + result);
Console.ReadKey();
}
static string BuildQuery(Criterion criterion)
{
return new QueryBuilder<Item>()
.Query(q => q
.QueryString(qs => qs
.Fields(item => item.Name, item => item.Description)
.Query(criterion.FullText)
)
)
.Filter(f => f
.And(a => a
.Range(r => r
.Field(item => item.Price)
// AsString extension allows to convert nullable values to string or null
.From(criterion.MinPrice.AsString())
.To(criterion.MaxPrice.AsString())
)
.Term(t => t
.Field(user => user.Active).Value(criterion.Active.AsString())
)
)
).BuildBeautified();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment