ElasticSearch NEST搜索
var client = ElasticsearchHelper.GetElasticClient("order");
QueryContainer termQuery = new TermQuery() { Field = "lastname", Value = "求和" };
var result = client.Search<Order>(s => s
.Aggregations(a => a
.Sum("my_sum_agg", sa => sa
.Field(p => p.TotalPrice)
)
)
);
var agg = result.Aggs.Sum("my_sum_agg");
var searchResults = client.Search<Order>(s => s
// .Query(termQuery) //带筛选条件
.Aggregations(r => r.Terms("firstname", r1 => r1.Field(r2 => r2.Lastname)
.OrderAscending("sumprice")
.Aggregations(y => y.Sum("sumprice", y1 => y1.Field(y2 => y2.TotalPrice))))));
var carTypes = searchResults.Aggs.Terms("firstname");
List<double> re=new List<double>();
foreach (var carType in carTypes.Items)
{
string key = carType.Key;
System.Console.WriteLine("key:" + key + " total:" + carType.Sum("sumprice").Value);
re.Add((double)carType.Sum("sumprice").Value);
}
//List<SumTotalPrice> orders = searchResults.Documents.ToList();
// System.Console.WriteLine(orders.Count() + " total:" + searchResults.Total);
//System.Console.WriteLine(searchResults.RequestInformation);
System.Console.ReadLine();
#endregion
#region 多条件精确匹配
var client = ElasticsearchHelper.GetElasticClient("order");
QueryContainer termQuery = new TermQuery() { Field = "firstname", Value = "测试" };
QueryContainer wholeWordQuery = new TermQuery() { Field = "lastname", Value = "addddd" };
//非索引字段。无法查询 此查询条件无效
QueryContainer termQuery1 = new TermQuery() { Field = "content", Value = " 天空是百度的1696" };
termQuery = (termQuery || wholeWordQuery) || termQuery1;
var searchResults = client.Search<Order>(s => s
.From(0)
.Size(10)
.Query(termQuery)
);
List<Order> orders = searchResults.Documents.ToList();
System.Console.WriteLine(orders.Count() + " total:" + searchResults.Total);
System.Console.ReadLine();
#endregion
#region 精确匹配
var client = ElasticsearchHelper.GetElasticClient("order");
var searchResults = client.Search<Order>(s => s
.From(0)
.Size(10)
.Query(q => q.Term(r => r.OnField(k => k.Firstname).Value("棉花")))
.Highlight(h => h.OnFields(e => e.OnField("firstname")
.PreTags("<b style='color:black'>")
.PostTags("</b>")))
.Sort(r => r.Descending().OnField(q => q.Createtime))
);
List<Order> orders = searchResults.Documents.ToList();
System.Console.WriteLine(orders.Count() + " total:" + searchResults.Total);
System.Console.ReadLine();
#endregion