C#嵌套弹性通用索引创建

时间:2018-10-24 07:42:16

标签: c# elasticsearch nest

我有一个通用的“创建”方法。此方法将按通用类型创建索引。但是我收到错误消息:

  1. 类型“ T”必须是引用类型,才能在通用类型或方法中用作参数“ T” 'MappingsDescriptor.Map(Func, ITypeMapping>)'

  2. 类型“ T”必须是引用类型,才能在通用类型或方法中用作参数“ T” 'ElasticClient.Index(T,Func, IIndexRequest>)'

    公共无效创建(T节点)     {
            如果(!_elasticClient.IndexExists(_indexName).Exists)         {             var indexSettings = new IndexSettings();             indexSettings.NumberOfReplicas = 1;             indexSettings.NumberOfShards = 3;

            var createIndexDescriptor = new CreateIndexDescriptor(_indexName)
           .Mappings(ms => ms
                           .Map<T>(m => m.AutoMap())
                    )
            .InitializeUsing(new IndexState() { Settings = indexSettings })
            .Aliases(a => a.Alias(aliasName));
    
            var response = _elasticClient.CreateIndex(createIndexDescriptor);
        }
    
        _elasticClient.Index<T>(node, idx => idx.Index(_indexName));
    }
    

2 个答案:

答案 0 :(得分:0)

尝试添加where T : class

public void Create<T>(T node) where T : class
    {        
        if (!_elasticClient.IndexExists(_indexName).Exists)
        {
            var indexSettings = new IndexSettings();
            indexSettings.NumberOfReplicas = 1;
            indexSettings.NumberOfShards = 3;

            var createIndexDescriptor = new CreateIndexDescriptor(_indexName)
           .Mappings(ms => ms
                           .Map<T>(m => m.AutoMap())
                    )
            .InitializeUsing(new IndexState() { Settings = indexSettings })
            .Aliases(a => a.Alias(aliasName));

            var response = _elasticClient.CreateIndex(createIndexDescriptor);
        }

        _elasticClient.Index<T>(node, idx => idx.Index(_indexName));
    }
}

我解决了我遇到的问题,请参阅下文。

答案 1 :(得分:0)

巢中的.Map<T>()方法对T使用类约束。您需要向通用T添加相同的类约束。

public void Create<T>(T node)
    where T: class
{
    // your code here
}