ElasticSearch NEST:通过指定json,通过ElasticClient创建索引

mca*_*ing 5 c# elasticsearch nest

我们允许客户在创建索引时定义自定义分析器.我们希望在json中指定它,以通过底层的ElasticSearch文档提供最大的灵活性和可理解性.

我想使用json字符串中定义的分析器,映射器等的任意描述来创建索引.使用sense,我的命令是

PUT /my_index
{
    "settings": 
    {
        "analysis": 
        {
            "char_filter" : 
            {
                "my_mapping" : 
                {
                    "type" : "mapping",
                    "mappings" : [".=>,", "'=>,"]
                }
            },
            "analyzer": 
            {
                "my_analyzer": 
                {
                    "type":         "custom",
                    "tokenizer":    "standard",
                    "filter":       ["lowercase" ],
                    "char_filter" : ["my_mapping"]
                }
            }
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我的代码看起来像

string json = RetrieveJson();
ElasticSearchClient client = InitializeClient();
client.CreateIndexUsingJson( json ); // this is the syntax I can't figure out
Run Code Online (Sandbox Code Playgroud)

这里的帖子试图通过实例化一个IndexSettings然后调用Add("analysis",json)来做到这一点,但Add不是我正在使用的ElasticSearch库版本的函数.

我能想象的选项包括:

  1. 不知何故使用ElasticClient.Raw.IndicesCreatePost或类似的东西
  2. 通过IndexSettingsConverter.ReadJson()将json字符串反序列化为IndexSettings对象,然后通过ElasticClient.CreateIndex(ICreateIndexRequest)应用它

这两种机制都有很少的文档.

我绝对试图避免使用CreateIndex的lambda函数版本,因为将用户的json转换为lamdba表达式会很麻烦,只能立即将它们转换回NEST中的json深度.

非常感谢上面#1或#2的其他选项或具体示例,以及解决此问题的推荐方法.

mca*_*ing 7

最简单的解决方案是从原始问题实施选项#1.

public void CreateIndex(string indexName, string json)
{
    ElasticClient client = GetClient();
    var response = _client.Raw.IndicesCreatePost(indexName, json);
    if (!response.Success || response.HttpStatusCode != 200)
    {
        throw new ElasticsearchServerException(response.ServerError);
    }
}
Run Code Online (Sandbox Code Playgroud)

在修改转换器和JsonReaders和JsonSerializers之后,我发现IndexSettingsConverter似乎没有将任意设置json正确反序列化为有效的IndexSettings对象.感觉到一个兔子洞,我采用了Manolis的建议,并想出如何直接对ElasticClient.IElasticsearchClient应用任意json,以避免必须对安全性和连接细节进行反向工程.

痛苦地努力得出这个结论,并且完全不可能没有完成大量无证的NEST代码.