作者:pigone | 来源:互联网 | 2023-05-19 06:58
使用NEST索引动态对象我正在构建一个API应用程序,它基本上允许用户构建一个文档,该文档可以根据需要进行结构化,并存储在Elasticsearch中。从本质上讲,我为用户提供了一
使用NEST索引动态对象
我正在构建一个API应用程序,它基本上允许用户构建一个文档,该文档可以根据需要进行结构化,并存储在Elasticsearch中。 从本质上讲,我为用户提供了一个简单的界面来访问我们的Elasticsearch实例。 我试图让实现尽可能简单。 这是我到目前为止所处理的问题。
预期身体的对象:
public class DocumentModel { public string Index { get; set; } public string Type { get; set; } public string Id { get; set; } [ElasticProperty(Type = FieldType.Nested)] public dynamic Document { get; set; } }
简单实施:
[HttpPost] [Route("")] public IHttpActionResult Post(DocumentModel document) { Uri nodeLocation = new Uri("http://localhost:9200"); IConnectionPool cOnnectionPool= new SniffingConnectionPool(new List { nodeLocation }); ConnectionSettings settings = new ConnectionSettings(connectionPool); ElasticClient esClient = new ElasticClient(settings); IIndexResponse result = esClient.Index(document, i => i .Index(document.Index) .Type(document.Type) .Id(document.Id)); return Ok(result.IsValid); }
这样可以正常工作,但它包含源中的索引,类型和ID。 我真正想做的只是在索引时提供这三条信息,但实际上只是索引document.Document,它是动态类型。 但是,这似乎与Nest不同,因为它在IDE中和编译时抛出错误:
“匿名函数或方法组不能用作动态绑定操作的组成值”
“如果没有先将lambda表达式转换为委托或表达式树类型,则不能将lambda表达式用作动态调度操作的参数”。
我怎样才能索引document.Document
? 有没有比使用动态类型更好的方法来处理未知结构的传入JSON文档?
有几种方法可以做到这一点。
尝试将文档索引为动态类型将不起作用,但您可以通过IndexRequest对象将其索引为对象。
dynamic dynamicDoc = new { /*fill in document format here*/ }; ElasticClient esClient = new ElasticClient(esSettings); IndexRequest
或者如果批量处理文件
List Documents = new List(); //Populate Documents BulkDescriptor descriptor = new BulkDescriptor(); foreach(var doc in Documents) { descriptor.Index
NEST(或更准确地说,Elasticsearch.Net)还有一个附加到ElasticClient类的.Raw方法变体,它可以索引原始JSON。 使用Raw.Index()让我们做这样的事情:
string documentJson = JsonConvert.SerializeObject(document.Document); ElasticsearchResponse result = esClient.Raw.Index(document.Index, document.Type, document.Id, documentJson);
响应的类型描述符是您期望响应所在的类型(字符串意味着您将具有序列化的json响应,您可以反序列化并执行某些操作)。 这允许我们回避整个对象类型问题,并且NEST将文档完全按预期索引到Elasticsearch中。
上述就是C#学习教程:使用NEST索引动态对象分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—编程笔记