代码之家  ›  专栏  ›  技术社区  ›  Lars Holdgaard

基于第三方ElasticSearch解决方案在解决方案中创建对象模型

  •  2
  • Lars Holdgaard  · 技术社区  · 8 年前

    处理JSON时,很容易创建C#模型。你也可以 Paste special 在Visual Studio中,或者使用许多可用的联机工具之一。

    ElasticSearch响应显然是JSON,这意味着,如果您可以得到响应的JSON,那么就可以开始了。然而,如果您只有一个连接字符串,并且只想将所有ElasticSearch对象“映射”到您的C#代码中,那么您该怎么做呢?

    我的问题:

    是否有一种方法可以查看ElasticSearch实例中的所有字段/数据,然后轻松获取JSON,从而可以获取强类型模型?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Evk    8 年前

    您可以查询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
                }
            }
        }
    }