You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Elasticsearch .NET客户端(v8.0)映射timestamp至@timestamp

Elasticsearch .NET客户端v8.0:POCO字段映射到@timestamp的解决方案

问题描述

我定义了如下POCO类:

public class HardwareData
{            
    public DateTime timestamp { get; set; }
    public int System_ErrorLevel { get; set; }
}

配置连接后,尝试用client.ElasticsearchClientSettings.AttributeMappings.Add("timestamp","@timestamp")或PropertyMappings将timestamp映射到Elasticsearch的@timestamp字段,但都无效。目前能通过ingest pipeline实现,但希望有更直接的方法。网上示例多基于NEST而非最新的ElasticsearchClient对象。未映射时调用以下代码会报错“@timestamp未设置”:

await client.IndexAsync(new IndexRequest<HardwareData>()
{
    Document = data
});

解决方案

在Elasticsearch .NET客户端v8.0中,推荐使用属性注解或客户端设置的字段映射规则来实现字段重命名,以下是两种可行方法:

方法一:使用DataMemberAttribute注解

直接在POCO的属性上添加[DataMember(Name = "@timestamp")]注解,指定Elasticsearch中的目标字段名:

using System.Runtime.Serialization;

public class HardwareData
{            
    [DataMember(Name = "@timestamp")]
    public DateTime timestamp { get; set; }
    public int System_ErrorLevel { get; set; }
}

此方法直接关联POCO属性与Elasticsearch字段,无需额外配置客户端,是最直观的实现方式。

方法二:通过DefaultFieldNameInferrer自定义全局映射

如果不想修改POCO类,可以在初始化ElasticsearchClientSettings时,自定义字段名推断逻辑,将指定属性名替换为@timestamp:

var settings = new ElasticsearchClientSettings(new Uri("http://localhost:9200"))
    .DefaultFieldNameInferrer(propertyName => 
    {
        return propertyName == "timestamp" ? "@timestamp" : propertyName;
    });

var client = new ElasticsearchClient(settings);

该规则会全局生效,所有POCO中名为timestamp的属性都会被自动映射为Elasticsearch的@timestamp字段。

验证写入

完成上述任一配置后,即可正常调用索引写入方法,无需额外处理:

await client.IndexAsync(new IndexRequest<HardwareData>()
{
    Document = data,
    Index = "your-target-index" // 需替换为实际的索引名称
});

内容的提问来源于stack exchange,提问作者shelbypereira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:35:07