当你处理JSON时,制作C#模型真的很容易。你可以在Visual Studio中使用Paste special
,也可以在线使用众多可用工具中的一种。
ElasticSearch响应显然是JSON,这意味着,如果你能得到响应的JSON,那么你很高兴。但是,如果您只有一个连接字符串并且只是想将所有ElasticSearch对象“映射”到您的C#代码中 - 您是如何做到的?
我的问题:
有没有办法在ElasticSearch实例中查看所有字段/数据,然后轻松获取JSON,以便获得强类型模型?
您可以查询elasticsearch以查找映射。映射将包含在C#中构建模型所需的所有信息(但我仍然需要手动构建它)。使用上一个问题中的数据库的示例:
var settings = new ConnectionSettings(new Uri("http://distribution.virk.dk/cvr-permanent"));
var client = new ElasticClient(settings);
// get mappings for all indexes and types
var mappings = client.GetMapping<JObject>(c => c.AllIndices().AllTypes());
foreach (var indexMapping in mappings.Indices) {
Console.WriteLine($"Index {indexMapping.Key.Name}"); // index name
foreach (var typeMapping in indexMapping.Value.Mappings) {
Console.WriteLine($"Type {typeMapping.Key.Name}"); // type name
foreach (var property in typeMapping.Value.Properties) {
// property name and type. There might be more useful info, check other properties of `typeMapping`
Console.WriteLine(property.Key.Name + ": " + property.Value.Type);
// some properties are themselves objects, so you need to go deeper
var subProperties = (property.Value as ObjectProperty)?.Properties;
if (subProperties != null) {
// here you can build recursive function to get also sub-properties
}
}
}
}