本文主要介绍.NET(C#)查询Elasticsearch索引结果,通过JSON.NET反序列化结果的方法。

1、示例查询结果

{
"took":31,
"timed_out":false,
"_shards": {
"total":91,
"successful":91,
"skipped":0,
"failed":0
},
"hits":{
"total":1,
"max_score":1.0,
"hits":[
{
"_index":"my-index",
"_type":"doc",
"_id":"TrxrZGYQRaDom5XaZp23",
"_score":1.0,
"_source":{
"my_id":"65a107ed-7325-342d-adab-21fec0a97858",
"host":"something",
"zip":"12345"
}
},
]
}
}

2、反序化用到Result类

public class Result
{
[JsonProperty(PropertyName = "my_id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "host")]
public string Host { get; set; }
[JsonProperty(PropertyName = "zip")]
public string PostalCode { get; set; }
}

3、使用 Json.Net的 LINQ-to-JSON API 获取指定的节点,然后将它们转换为结果列表:

var results = JToken.Parse(response.Body)
.SelectTokens("hits.hits[*]._source")
.Select(t => t.ToObject<Result>())
.ToList();

4、完整的代码:

using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
public class Program
{
public static void Main()
{
string json = @"
{
""took"": 31,
""timed_out"": false,
""_shards"": {
""total"": 91,
""successful"": 91,
""skipped"": 0,
""failed"": 0
},
""hits"": {
""total"": 1,
""max_score"": 1.0,
""hits"": [
{
""_index"": ""my-index"",
""_type"": ""doc"",
""_id"": ""TrxrZGYQRaDom5XaZp23"",
""_score"": 1.0,
""_source"": {
""my_id"": ""65a107ed-7325-342d-adab-21fec0a97858"",
""host"": ""something"",
""zip"": ""12345""
}
},
{
""_index"": ""my-index"",
""_type"": ""doc"",
""_id"": ""jhgDtrEYHrjgJafgRy456"",
""_score"": 0.95,
""_source"": {
""my_id"": ""52f0be23-1d2f-4779-bde9-32fc9e50168e"",
""host"": ""something else"",
""zip"": ""06789""
}
}
]
}
}";
var results = JToken.Parse(json)
.SelectTokens("hits.hits[*]._source")
.Select(t => t.ToObject<Result>())
.ToList();
foreach (var result in results)
{
Console.WriteLine("Id: " + result.Id);
Console.WriteLine("Host: " + result.Host);
Console.WriteLine("PostalCode: " + result.PostalCode);
Console.WriteLine();
}
}
}
public class Result
{
[JsonProperty(PropertyName = "my_id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "host")]
public string Host { get; set; }
[JsonProperty(PropertyName = "zip")]
public string PostalCode { get; set; }
}