var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200")); var connectionSettings = new ConnectionSettings( pool, sourceSerializer: (builtin, settings) => new VanillaSerializer()); var client = new ElasticClient(connectionSettings);
注入序列化器使用委托的原因:
有的时候,你的 POCO 类由于某些原因,需要内嵌 NEST 类型(如你可能需要用到过滤,这个时候你希望获取文档中的 _source),如下:
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200")); var connectionSettings = new ConnectionSettings(pool, sourceSerializer: JsonNetSerializer.Default); var client = new ElasticClient(connectionSettings);
JsonNetSerializer.Default 是语法糖,实际为:
1 2 3 4 5
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200")); var connectionSettings = new ConnectionSettings( pool, sourceSerializer: (builtin, settings) => new JsonNetSerializer(builtin, settings)); var client = new ElasticClient(connectionSettings);
publicclassMyDocument { publicint Id { get; set; }
publicstring Name { get; set; }
publicstring FilePath { get; set; }
publicint OwnerId { get; set; }
public IEnumerable<MySubDocument> SubDocuments { get; set; } }
publicclassMySubDocument { publicstring Name { get; set; } }
注入序列化器:
1 2 3 4 5 6 7 8
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200")); var connectionSettings = new ConnectionSettings( pool, connection: new InMemoryConnection(), sourceSerializer: (builtin, settings) => new MyFirstCustomJsonNetSerializer(builtin, settings)) .DefaultIndex("my-index");
var client = new ElasticClient(connectionSettings);
索引一份文档到 ES 中
1 2 3 4 5 6 7 8
var document = new MyDocument { Id = 1, Name = "My first document", OwnerId = 2 };
var ndexResponse = client.IndexDocument(document);
以上文档将会被序列化为:
1 2 3 4 5 6 7
{ "id":1, "name":"My first document", "file_path":null, "owner_id":2, "sub_documents":null }
protectedoverride ConnectionSettingsAwareContractResolver CreateContractResolver() => new MySecondCustomContractResolver(ConnectionSettings); }
重写 resolver
注入自定义序列化器
1 2 3 4 5 6 7 8
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200")); var connectionSettings = new ConnectionSettings( pool, connection: new InMemoryConnection(), sourceSerializer: (builtin, settings) => new MySecondCustomJsonNetSerializer(builtin, settings)) .DefaultIndex("my-index");
var client = new ElasticClient(connectionSettings);
添加以下文档到 ES 中
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var document = new MyDocument { Id = 1, Name = "My first document", OwnerId = 2, SubDocuments = new [] { new MySubDocument { Name = "my first sub document" }, new MySubDocument { Name = "my second sub document" }, } };
var ndexResponse = client.IndexDocument(document);
序列化结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
{ "$type":"Tests.ClientConcepts.HighLevel.Serialization.GettingStarted+MyDocument, Tests", "id":1, "name":"My first document", "ownerId":2, "subDocuments":[ { "name":"my first sub document" }, { "name":"my second sub document" } ] }