Search code examples
elasticsearchnest

How to retrieve the serialized field name of an Elasticsearch Nest.Field


I want to get the field name of a field which is created with Infer.Field<MyDocument>(doc => doc.StringField1).

Example code:

using System;
using Nest;
using Xunit;

namespace Elasticsearch.Tests
{
    public class MyDocument
    {
        public string StringField1 { get; set; }
    }

    public class SerializeField
    {

        [Fact]
        public void TestFieldName()
        {
            var connectionSettings = new ConnectionSettings(new Uri("http://myesdomain.com:9200"));
            var client = new ElasticClient(connectionSettings);

            var stringField = Infer.Field<MyDocument>(doc => doc.StringField1);
            // TODO: Code to get then name of stringField when serialized
        }
    }
}

Can I leaverage the client in order to serialize the name of the stringField as it would do in any request?


Solution

  • There is a better solution that uses a Nest.FieldResolver.

    using System;
    using Nest;
    using Xunit;
    
    namespace Elasticsearch.Tests
    {
        public class MyDocument
        {
            public string StringField1 { get; set; }
        }
    
        public class TestClass
        {
    
            [Fact]
            public void TestFieldName()
            {
                var connectionSettings = new ConnectionSettings(new Uri("http://myesdomain.com:9200"));
                var fieldResolver = new FieldResolver(connectionSettings);
                var stringField = Infer.Field<MyDocument>(doc => doc.StringField1);
                var fieldName = fieldResolver.Resolve(stringField);
    
                Assert.Equal("stringField1", fieldName);
            }
        }
    }