總體思路是:
利用json序列化的别名方法,反序列化到不同的字段上;
因為别名方法不支援多個别名,是以不得不根據不同的type,定義了多套适配内容。
最終在屬性上進行選擇。
本示例ElasticSearch傳回的json串形如:
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 3.4698925,
"hits": [
{
"_index": "user",
"_type": "userinfo",
"_id": "1031014642252640",
"_score": 3.4698925,
"_source": {
"uid": 1031014642252640,
"level": 20
}
}
,
{
"_index": "user",
"_type": "good",
"_id": "1",
"_score": 0.06378032,
"_source": {
"id": 1,
"name": "good luck"
}
}
]
}
}
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TestQuery
{
[Serializable]
public class Show
{
/* A實體反序列化内容 */
[JsonProperty(PropertyName = "uid")]
private string title_1;
[JsonProperty(PropertyName = "level")]
private string content_1;
/* B實體反序列化内容 */
[JsonProperty(PropertyName = "id")]
private string title_2;
[JsonProperty(PropertyName = "name")]
private string content_2;
/* AB實體反序列化内容彙總傳回 */
public string Title
{
get
{
return title_1 ?? title_2;
}
}
public string Content
{
get
{
return content_1 ?? content_2;
}
}
}
class Program
{
static void Main(string[] args)
{
var query = new QueryBuilder<Object>()
.Query(q =>
q.Bool(b =>
b.Should(m =>
m.Term(tm =>
{
tm.Field("uid");
tm.Value("1031014642252640");
return tm;
}).Custom(@"{
""exists"": {
""field"": ""name""
}
}")
)
)
)
.From(0)
.Size(100)
//.Sort(s => s.Field(UserInfoField.level, SortDirection.desc))
.BuildBeautified();
Console.WriteLine(query);
List<Show> list = new List<Show>();
var cmd = new SearchCommand("user");
var client = new ElasticConnection("localhost", 9200);
var operationResult = client.Post(cmd, query);
var serializer = new JsonNetSerializer();
var hits = serializer.ToSearchResult<Show>(operationResult).hits;
var serializerResult = hits.hits;
//頁面顯示實體
//
foreach (var item in serializerResult)
{
list.Add(item._source);
}
}
}
}
轉載于:https://www.cnblogs.com/thaughtZhao/p/5545770.html