如何检索Elasticsearch Nest.Field的序列化字段名



我想获得Infer.Field<MyDocument>(doc => doc.StringField1)创建的字段的字段名。

示例代码:

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
}
}
}

我可以离开客户端以便序列化stringField的名称,就像在任何请求中一样吗?

幸运的是我自己找到了答案:

短:

client.SourceSerializer.Serialize(stringField, ms);

完成:

using System;
using System.IO;
using System.Text;
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);
string fieldName;
using (var ms = new MemoryStream())
{
client.SourceSerializer.Serialize(stringField, ms);
ms.Position = 0;
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
fieldName = reader.ReadToEnd();
}
}
Assert.Equal(""stringField1"", fieldName);
}
}
}

有一个更好的解决方案,使用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);
}
}
}

相关内容

  • 没有找到相关文章

最新更新