【问题标题】:NEST 5.5 Attribute mapping and custom JsonConverter not workingNEST 5.5 属性映射和自定义 JsonConverter 不起作用
【发布时间】:2017-08-11 11:29:56
【问题描述】:

我们使用 Nest 5.5.0 和属性映射在 Elasticsearch 中创建索引。作为我们某些属性的一部分,我们正在使用自定义 JsonConverters。

我们正在从 1.7.3 迁移,该映射已正确处理。升级后,我们可以在映射中看到它已经映射了字段,没有使用转换器。当我们然后索引一个文档时,转换器被使用并且索引操作失败。

例子:

Nest 和 Elasticsearch 1.7.3

// code
public class MyItem
{
    [JsonProperty("start")]
    [JsonConverter(typeof(LocalTimeConverter))]
    public LocalTime Start { get; set; }
}

// index creation
elasticClient.CreateIndex("indexname", d => d.AddMapping<MyItem>(m => m.MapFromAttributes()))

// generated mapping (mapped as how the JsonConverter would output it)
"myitem": {
    "start": {
        "type": "string"
    }
}

Nest 和 Elasticsearch 5.5.0

// code
public class MyItem
{
    [JsonProperty("start")]
    [JsonConverter(typeof(LocalTimeConverter))]
    public LocalTime Start { get; set; }
}

// index creation
elasticClient.CreateIndexAsync(IndexName<T>(), d => d.Mappings(m => m.Map<MyItem>(mm => mm.AutoMap())));

// generated mapping (essentially a serialized version of the class)
"myitem": {
     "properties": {
        "clockHourOfHalfDay": { "type": "integer"},
        ...
        ...
        "hour": {"type": "integer" }
}

注意事项:

  • Lo​​calTime 是 NodaTime 库中的一个类
  • 自定义 LocalTimeConverter 采用 LocalTime 并输出一个字符串

如何强制 Nest 5.5.0 在生成映射时考虑 JsonConverter 属性?

【问题讨论】:

    标签: c# elasticsearch nest


    【解决方案1】:

    要将LocalTime 映射为keyword 类型(我认为这是您想要的,不会被分析,但仍然可以被索引和搜索),您可以使用

    public class MyItem
    {
        [JsonProperty("start")]
        [JsonConverter(typeof(LocalTimeConverter))]
        [Keyword]
        public LocalTime Start { get; set; }
    }
    

    并按照您当前的操作创建索引和映射。

    如果您希望默认为 NEST 驼峰式属性名称,您也可以省略 JsonPropertyAttribute

    这会产生映射

    {
      "mappings": {
        "myitem": {
          "properties": {
            "start": {
              "type": "keyword"
            }
          }
        }
      }
    }
    

    【讨论】:

    • 谢谢!这确实有效。如果属性是List&lt;LocalDate&gt;,你会怎么做?我想将其映射为字符串列表,而不是对象列表。
    • 你会以同样的方式映射它; Elasticsearch 不区分属性的单个值或相同类型的多个值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2017-09-08
    • 2020-01-22
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多