面试题答案
一键面试using Nest;
public class ElasticsearchInitializer
{
public static void CreateIndex()
{
var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
.DefaultIndex("products");
var client = new ElasticClient(settings);
var indexExistsResponse = client.Indices.Exists("products");
if (!indexExistsResponse.Exists)
{
var createIndexResponse = client.Indices.Create("products", c => c
.Map<Product>(m => m
.AutoMap()
)
);
}
}
}
public class Product
{
public string Name { get; set; }
public float Price { get; set; }
}
上述代码实现了以下功能:
- 创建
ConnectionSettings
连接到 Elasticsearch 服务器,并设置默认索引为products
。 - 使用
ElasticClient
检查名为products
的索引是否存在。 - 如果索引不存在,则创建索引,并通过
AutoMap
方法自动映射Product
类的属性(Name
和Price
)到 Elasticsearch 文档的字段。Product
类包含name
(字符串类型)和price
(浮点类型)两个属性,对应索引中的字段。实际应用中,http://localhost:9200
需替换为实际的 Elasticsearch 服务器地址。