ElasticSearch 2.X升級到6.X遇到的幾個問題

1.IndexExists檢測索引是否存在,更簡潔了,能夠這樣json

_ElasticClient.IndexExists(indices : indexName).Exists

2.索引數據的時候,若是數據是個字符串json,那麼索引後查看數據是有問題的,索引的數據須要是個Model對象,此狀況是我的遇到的,不肯定是否有其餘操做方法c#

3.若是索引數據是作了路由處理的話,那麼使用Id搜索或者刪除也必須加上路由信息,否則會404找不到的,此狀況只針對Id搜索或刪除jsonp

_ElasticClient.Get(new DocumentPath<T>(esId), s => s.Type(_EsType).Routing(routing))

_ElasticClient.DeleteAsync(new DeleteRequest(_ElasticClient.ConnectionSettings.DefaultIndex, _EsType, esId) { Routing = routing });

 4.es.dll 6.x的使用雖然擺脫了Newtonsoft.Json的依賴,但也出現一些新的問題,序列化會和Newtonsoft不太同樣,致使老項目沒法直接使用,好比c# Model中的屬性「Name」標記了jsonproperty["nm"],但6.x中索引的數據並無使用nm,依然是Name,這就是6.x中自帶序列化的問題。對於這個狀況,6.x其實提供了一個接口IElasticsearchSerializer,只須要去實現而且使用便可,使用方法以下ui

var _ConnectionPool = new StaticConnectionPool(uris);
var _ConnectionConfig = new ConnectionSettings(_ConnectionPool, sourceSerializer: (builtin, settingss) => new JsonNetSerializer());
var _ElasticClient = new ElasticClient(_ConnectionConfig.DefaultIndex("IndexName").DefaultFieldNameInferrer((name) => name));

 JsonNetSerializer 是新建的實現類,繼承IElasticsearchSerializer,實現以下spa

public class JsonNetSerializer : IElasticsearchSerializer
{
    private static JsonSerializer serializer = JsonSerializer.CreateDefault();
    private static JsonSerializer indentedSerializer = 
        JsonSerializer.CreateDefault(new JsonSerializerSettings
        {
            Formatting = Newtonsoft.Json.Formatting.Indented
        });
    
    public object Deserialize(Type type, Stream stream)
    {
        var streamReader = new StreamReader(stream);
        var reader = new JsonTextReader(streamReader);
        return serializer.Deserialize(reader, type);
    }

    public T Deserialize<T>(Stream stream)
    {
        return (T)Deserialize(typeof(T), stream);
    }

    public Task<object> DeserializeAsync(Type type, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
    {
        var o = Deserialize(type, stream);
        return Task.FromResult(o);
    }

    public Task<T> DeserializeAsync<T>(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
    {
        var o = Deserialize<T>(stream);
        return Task.FromResult(o);
    }

    public void Serialize<T>(T data, Stream stream, SerializationFormatting formatting = SerializationFormatting.Indented)
    {
        var writer = new StreamWriter(stream);
        if (formatting == SerializationFormatting.Indented)
            indentedSerializer.Serialize(writer, data, typeof(T));
        else
            serializer.Serialize(writer, data, typeof(T));    
            
        writer.Flush();
    }

    public Task SerializeAsync<T>(T data, Stream stream, SerializationFormatting formatting = SerializationFormatting.Indented, CancellationToken cancellationToken = default(CancellationToken))
    {
        Serialize(data, stream, formatting);
        return Task.CompletedTask;
    }
}
相關文章
相關標籤/搜索