总体思路是:

利用json序列化的别名方法,反序列化到不同的字段上;

因为别名方法不支持多个别名,所以不得不根据不同的type,定义了多套适配内容。

最终在属性上进行选择。

本示例ElasticSearch返回的json串形如:

{

    "took": ,
"timed_out": false,
"_shards": {
"total": ,
"successful": ,
"failed":
},
"hits": {
"total": ,
"max_score": 3.4698925,
"hits": [
{
"_index": "user",
"_type": "userinfo",
"_id": "",
"_score": 3.4698925,
"_source": {
"uid": ,
"level":
}
}
,
{
"_index": "user",
"_type": "good",
"_id": "",
"_score": 0.06378032,
"_source": {
"id": ,
"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("");
return tm;
}).Custom(@"{
""exists"": {
""field"": ""name""
}
}")
)
)
)
.From()
.Size()
//.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", );
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);
} }
}
}
05-11 13:32