Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PlainElastic.Net 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 User
{
public int Id { get; set; }
public bool Active { get; set; }
public string Name { get; set; }
public string Alias { get; set; }
}
class Program
{
static void Main(string[] args)
{
var connection = new ElasticConnection("localhost", 9200);
var serializer = new JsonNetSerializer();
// Add User document to http://localhost:9200/twitter/user/ index
var addedUser = new User
{
Id = 1,
Active = true,
Name = "John Smith",
Alias = "Johnnie"
};
string userJson = serializer.Serialize(addedUser);
connection.Put(Commands.Index("twitter", "user", id: addedUser.Id.AsString()).Refresh(),
userJson);
// Construct Query
string query = new QueryBuilder<User>()
.Query(q => q
.Bool(b => b
.Must(m => m
.QueryString(qs => qs
.Fields(user => user.Name, user => user.Alias).Query("John")
)
.Prefix(p => p
.Field(user => user.Alias).Prefix("john")
)
)
)
)
.Filter(f => f
.Term(t => t
.Field(user => user.Active).Value(true.ToString())
)
).BuildBeautified();
string result = connection.Post(Commands.Search("twitter", "user"), query);
User foundUser = serializer.ToSearchResult<User>(result).Documents.First();
Console.WriteLine("Name " + foundUser.Name);
Console.WriteLine("Alias " + foundUser.Alias);
Console.WriteLine("Query " + query);
Console.WriteLine("JSON result " + result);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment