Working with dynamic types is similar in NEST 5.x as it was in NEST 1.x; some of the client API has changed a little in between these versions but the premise is still the same.
Here's an example
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var defaultIndex = "default-index";
var connectionSettings = new ConnectionSettings(pool)
.DefaultIndex(defaultIndex);
var client = new ElasticClient(connectionSettings);
// delete the index if it already exists
if (client.IndexExists(defaultIndex).Exists)
client.DeleteIndex(defaultIndex);
client.CreateIndex(defaultIndex);
// create an anonymous type assigned to a dynamically typed variable
dynamic instance = new
{
Name = "Russ",
CompanyName = "Elastic",
Date = DateTimeOffset.UtcNow
};
// cast the instance to object to index, explicitly
// specify the document type and index
var indexResponse = client.Index((object)instance, i => i
.Type("my_type")
.Index(defaultIndex)
);
// fetch the document just indexed
var getResponse = client.Get<dynamic>(indexResponse.Id, g => g
.Type(indexResponse.Type)
.Index(indexResponse.Index)
);
The request and response JSON for this look like
HEAD http://localhost:9200/default-index?pretty=true
Status: 200
------------------------------
DELETE http://localhost:9200/default-index?pretty=true
Status: 200
{
"acknowledged" : true
}
------------------------------
PUT http://localhost:9200/default-index?pretty=true
{}
Status: 200
{
"acknowledged" : true,
"shards_acknowledged" : true
}
------------------------------
POST http://localhost:9200/default-index/my_type?pretty=true
{
"name": "Russ",
"companyName": "Elastic",
"date": "2017-03-11T04:03:53.0561954+00:00"
}
Status: 201
{
"_index" : "default-index",
"_type" : "my_type",
"_id" : "AVq7iXhpc_F3ya7MTJiU",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"created" : true
}
------------------------------
GET http://localhost:9200/default-index/my_type/AVq7iXhpc_F3ya7MTJiU?pretty=true
Status: 200
{
"_index" : "default-index",
"_type" : "my_type",
"_id" : "AVq7iXhpc_F3ya7MTJiU",
"_version" : 1,
"found" : true,
"_source" : {
"name" : "Russ",
"companyName" : "Elastic",
"date" : "2017-03-11T04:03:53.0561954+00:00"
}
}
------------------------------
This demonstrates that the document is indexed as expected, and the original source document can be retrieved.
The low level client can be accessed on the high level client in NEST 2.x and 5.x through the .LowLevel
property, so you can do something similar to the linked question with
dynamic instance = new
{
Id = "id",
Index = defaultIndex,
Type = "my_type",
Document = new
{
Name = "Russ",
CompanyName = "Elastic",
Date = DateTimeOffset.UtcNow
}
};
string documentJson = client.Serializer.SerializeToString((object)instance.Document);
var result = client.LowLevel.Index<string>(instance.Index, instance.Type, instance.Id, documentJson);