如何通过elasticsearch get将数据导入模型

时间:2015-01-20 10:13:00

标签: c# elasticsearch

public class News
{
    public string author { get; set; }
    public string title { get; set; }
    public DateTime timestamp{ get; set; }
    public string content { get; set; }
    public bool forstudents { get; set; }

    public List<link> links { get; set; }
    public List<imgs> imgs { get; set; }
}

public class link
{
    public string name { get; set; }
    public string value { get; set; }
}
public class imgs
{
    public string name { get; set; }
    public string value { get; set; }
}

这是我的模型描述然后我连接到服务器

var _esServer = new ElasticSearchServer("http://localhost:9200");
var _esIndex = _esServer.GetIndex("campusoffice");
var news = _esIndex.Get<News>("/news", int.MaxValue);

它应该让一切正常,但

他没有映射列表元素中的名称和值

{
  "author": "soulseak",
  "title": "Awsome",
  "timestamp": 20130201,
  "content": "Erster",
  "forstudents": true,
  "links": {
    "myhome": "http://test.de"
  },
  "imgs": {
    "myhome": "http://test.de"
  }
}

问题是如何告诉他我的名字和价值是什么,myhome的名字和价值网址

1 个答案:

答案 0 :(得分:0)

您可以这样做:

public class User {
    public User(string json) {
        var jsonObject = Json.Decode(json);
        MyName = (string)jsonObject.user.name;
        MyTeamName = (string)jsonObject.user.teamname;
        MyEmail = (string)jsonObject.user.email;
        Players = (DynamicJsonArray) jsonObject.user.players;
    }

    public string MyName{ get; set; }
    public string MyTeamName  { get; set; }
    public string MyEmail{ get; set; }
    public Array Players { get; set; }
}

但是需要手动分配值。

使用您的模型的示例(仅基于0索引,您需要编写循环)但使用直接的RestFul调用:

var url = "http://localhost:9200/campusoffice/news";
var client = new WebClient();
var json = client.DownloadString(url);
var jsonObject = Json.Decode(json);

var links = (DynamicJsonArray) jsonObject.links;
var imgs = (DynamicJsonArray) jsonObject.imgs;
var news = new News 
   { author = (string)jsonObject.author,
     links = new List<link>() };

var aLink = new link { name = (string)links[0].myhome, value = 
         (string)imgs[0].myhome };

news.links.Add(aLink);

我粗略地输入了这个而没有编译/测试但是应该给你一个想法。