MST
星途 面试题库

面试题:C# 中如何在 Elasticsearch 集成时处理基本的索引创建

在 C# 项目中集成 Elasticsearch,假设你要创建一个名为 'products' 的索引,并且该索引包含 'name'(字符串类型)和 'price'(浮点类型)两个字段,请写出关键的 C# 代码片段实现此功能。
31.8万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
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; }
}

上述代码实现了以下功能:

  1. 创建 ConnectionSettings 连接到 Elasticsearch 服务器,并设置默认索引为 products
  2. 使用 ElasticClient 检查名为 products 的索引是否存在。
  3. 如果索引不存在,则创建索引,并通过 AutoMap 方法自动映射 Product 类的属性(NamePrice)到 Elasticsearch 文档的字段。Product 类包含 name(字符串类型)和 price(浮点类型)两个属性,对应索引中的字段。实际应用中,http://localhost:9200 需替换为实际的 Elasticsearch 服务器地址。