Skip to content

Instantly share code, notes, and snippets.

@Yegoroff
Created November 27, 2013 16:53
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/7679120 to your computer and use it in GitHub Desktop.
Save Yegoroff/7679120 to your computer and use it in GitHub Desktop.
Elastic Search And/Or filters
using System;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
namespace EsAndOrFiltersSample
{
class Program
{
static void Main(string[] args)
{
var connection = new ElasticConnection("localhost", 9200);
var serializer = new JsonNetSerializer();
// Add sample object to ElasticSearch Index
var myObject = new MyObject {
Field1 = "1",
Field2 = "2",
Field3 = "3",
Field4 = "4",
Field5 = "5",
Field6 = "6"
};
string myObjectJson = serializer.ToJson(myObject);
connection.Put(Commands.Index("myindex", "mytype", id: "id1").Refresh(), myObjectJson);
// Build and/or query "1 and 2 and {3 or 4 or 5} and 6"
string query = new QueryBuilder<MyObject>()
.Filter(f => f
.And(and => and
.Term( t=>t.Field(myObj => myObj.Field1).Value("1"))
.Term(t => t.Field(myObj => myObj.Field2).Value("2"))
.Or(or => or
.Term(t => t.Field(myObj => myObj.Field3).Value("3"))
.Term(t => t.Field(myObj => myObj.Field4).Value("4"))
.Term(t => t.Field(myObj => myObj.Field5).Value("5"))
)
.Term(t => t.Field(myObj => myObj.Field6).Value("6"))
)
)
.Size(10)
.BuildBeautified();
Console.WriteLine("QUERY: \r\n" + query);
// Execute query and deserialize results.
string results = connection.Post(Commands.Search("myindex", "mytype"), query);
SearchResult<MyObject> foundMyObjects = serializer.ToSearchResult<MyObject>(results);
// Print results
Console.WriteLine("\r\nFOUND OBJECTS: \r\n");
foreach (var foundMyObject in foundMyObjects.Documents)
{
Console.WriteLine("Field1: " + foundMyObject.Field1 + " Field2: " + foundMyObject.Field2);
}
Console.ReadKey();
}
}
public class MyObject
{
public string Field1 { get; set;}
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
public string Field5 { get; set; }
public string Field6 { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment