我从2年前发现了这个问题Index a dynamic object using NEST。
我基本上有完全相同的问题,但使用的是NEST 5.0。所提出的溶剂在最新版本中不再有效。
答案 0 :(得分:3)
使用动态类型在NEST 5.x中与在NEST 1.x中类似;一些客户端API在这些版本之间有所改变,但前提仍然是相同的。
这是一个例子
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)
);
此请求和响应JSON看起来像
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"
}
}
------------------------------
这表明文档按预期编制索引,并且可以检索原始源文档。
可以通过.LowLevel
属性在NEST 2.x和5.x中的高级客户端访问低级客户端,因此您可以使用
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);