用 C# 连接 Elasticsearch,最常用、官方推荐的方式就是使用 NEST(.NET Elasticsearch Client)——它是 Elastic 官方维护的高级强类型客户端,封装了 REST API,支持 LINQ 查询、自动序列化、连接池、重试等生产级特性。
1. 安装 NEST 包
在项目中通过 NuGet 安装最新稳定版(注意匹配你的 Elasticsearch 服务版本):
Visual Studio:NuGet 包管理器中搜索NEST,安装最新版(如
7.17.0对应 ES 7.x;
8.12.0对应 ES 8.x) .NET CLI 命令:
dotnet add package NEST --version 8.12.0⚠️ 版本必须与 Elasticsearch 服务端主版本一致(如 ES 8.12 → NEST 8.12),否则可能报错或功能异常
2. 创建连接客户端
使用
ElasticClient实例连接集群。推荐用
ConnectionSettings配置连接信息:
var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
.DefaultIndex("my-products") // 设置默认索引名(可选)
.BasicAuthentication("elastic", "password"); // ES 8.x 默认启用安全认证,需填用户名密码
<p>var client = new ElasticClient(settings);
本地单节点:用 http://localhost:9200云服务(如 Elastic Cloud):填提供的云地址,通常带 HTTPS 和端口 ES 8.x 启用了 TLS + Basic Auth,务必配置
BasicAuthentication或
CertificateAuthentication生产环境建议启用连接池(
new SingleNodeConnectionPool或
new SniffingConnectionPool)和请求超时
3. 索引文档(添加/更新数据)
定义一个 C# 类并映射到 ES 文档(属性名默认转为小驼峰,可用
[Text]、
[Keyword]等特性控制字段类型):
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public DateTime CreatedAt { get; set; }
}
插入或替换文档:
var product = new Product { Id = 1, Name = "Laptop", Price = 999.99m, CreatedAt = DateTime.UtcNow };
var response = await client.IndexAsync(product, idx => idx.Index("my-products"));
if (response.IsValid) Console.WriteLine("写入成功");
不指定 ID 会由 ES 自动生成;指定 ID 则是“插入或更新”(upsert 行为)
首次写入会自动创建索引(按默认 mapping),但生产环境建议提前用 PutIndex显式定义 mapping
4. 查询文档(简单检索 & 条件查询)
支持 Fluent API 和 LINQ 两种风格。例如按 ID 获取:
var getResponse = await client.GetAsync<Product>(1, idx => idx.Index("my-products"));
if (getResponse.Found) Console.WriteLine(getResponse.Source.Name);
条件搜索(比如价格大于 500 的商品):
var searchResponse = await client.SearchAsync<Product>(s => s
.Query(q => q
.Range(r => r
.Field(f => f.Price)
.GreaterThan(500)
)
)
);
foreach (var hit in searchResponse.Hits)
Console.WriteLine($"{hit.Source.Name}: ${hit.Source.Price}");
所有查询方法都返回 IResponse或
ISearchResponse<t></t>,记得检查
.IsValid和
.ServerError复杂查询可用
Bool()组合 must/should/must_not,支持分页(
.From().Size())、排序、高亮等 调试时可打印
response.DebugInformation查看实际发送的 JSON 请求
基本上就这些。NEST 封装得足够友好,只要版本对齐、认证配对、类型映射合理,日常增删改查非常直观。遇到报错优先看
response.DebugInformation和 HTTP 状态码(比如 401=认证失败,400=DSL 错误,404=索引不存在)。
