首页 > 解决方案 > ElasticSearch 返回的嵌套属性未映射到 C# 类

问题描述

我在 ElasticSearch 中有一个嵌套对象,我试图将它映射到 C# 中的列表中,但它总是返回一个NULL

我的 C# 类如下所示:

    [ElasticsearchType(RelationName = "part")]
    public class Product 
    {
         [JsonPropertyName("PartNumber")]
         [Keyword(Name = "PartNumber")]
         public string ProductNumber { get; set; }

         [JsonPropertyName("Pricing")]
         [Nested]
         public IList<PartPricing> Pricing { get; set; }
    }

    [ElasticsearchType(RelationName = "Pricing")]
    public class PartPricing
    {
        [Keyword(Name = "Application")]
        public string Application { get; set; }

        [JsonPropertyName("BasePrice")]
        [Number(NumberType.Double, Name = "BasePrice")]
        public decimal BasePrice { get; set; }

        [Boolean(Name = "IsFreeShipping")]
        public bool IsFreeShipping { get;set; }

        [JsonPropertyName("CustomerPrice")]
        [Number(NumberType.Double, Name = "CustomerPrice")]
        public decimal CustomerPrice { get; set; }
    }   

当我使用 NEST C# 构建查询时,然后运行以下命令

var response = _context.Client.Search<T>(searchDescriptor);

如果我查看响应中的 DEBUG 信息,REQUEST 如下所示:

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "PartNumber": {
                            "value": "1001"
                        }
                    }
                }
            ]
        }
    },
    "_source": {
        "includes": [
            "id",
            "PartNumber",
            "Pricing"
        ]
    }
}

响应如下所示:

{
    "took": 63,
    "timed_out": false,
    "_shards": {
        "total": 6,
        "successful": 6,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": null,
        "hits": [
            {
                "_index": "parts",
                "_type": "part",
                "_id": "~111111",
                "_score": null,
                "_source": {
                    "id": 1234
                    "PartNumber": "1001",
                    "Pricing": [
                        {
                            "BasePrice": 95.0,
                            "IsFreeShipping": true,
                            "Application": "TEST",
                            "CustomerPrice": 161.5
                        }
                    ]
                },
                "sort": [
                    2,
                    470
                ]
            }
        ]
    }
}

所以我可以看到定价信息是从查询中返回的,但它没有正确映射到我的 C# 类中,因为 Pricing 属性总是NULL. 我猜我的类定义有问题,但我不确定是什么。这是我第一次使用 ElasticSearch。我可以毫无问题地返回其他十进制或字符串值,但嵌套值根本不返回。

标签: c#elasticsearchnest

解决方案


我最终能够弄清楚这个问题。我想在使用 NESTED 属性时,还需要添加一个 name 属性,因此在我的 Product 类中,我需要按如下方式创建该属性

[Nested(Name = "Pricing")]


推荐阅读