最常用且官方推荐的方式是使用 NEST 客户端,需匹配 Elasticsearch 服务版本安装对应 NuGet 包,通过 ElasticClient 配置连接、索引文档和执行查询,支持强类型、LINQ、自动序列化与生产级特性。
用 C# 连接 Elasticsearch,最常用、官方推荐的方式就是使用 NEST(.NET Elasticsearch Client)——它是 Elastic 官方维护的高级强类型客户端,封装了 REST API,支持 LINQ 查询、自动序列化、连接池、重试等生产级特性。
在项目中通过 NuGet 安装最新稳定版(注意匹配你的 Elasticsearch 服务版本):
NEST,安装最新版(如 7.17.0 对应 ES 7.x;8.12.0 对应 ES 8.x)dotnet add package NEST --version 8.12.0
使用 ElasticClient 实例连接集群。推荐用 ConnectionSettings 配置连接信息:
var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
.DefaultIndex("my-products") // 设置默认索引名(可选)
.BasicAuthentication("elastic", "password"); // ES 8.x 默认启用安全认证,需填用户名密码
var client = new ElasticClient(settings);
http://localhost:9200
BasicAuthentication
或 CertificateAuthentication
new SingleNodeConnectionPool 或 new SniffingConnectionPool)和请求超时定义一个 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("写入成功");
PutIndex 显式定义 mapping支持 Fluent API 和 LINQ 两种风格。例如按 ID 获取:
var getResponse = await client.GetAsync(1, idx => idx.Index("my-products")); if (getResponse.Found) Console.WriteLine(getResponse.Source.Name);
条件搜索(比如价格大于 500 的商品):
var searchResponse = await client.SearchAsync(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,记得检查 .IsValid 和 .ServerError
Bool() 组合 must/should/must_not,支持分页(.From().Size())、排序、高亮等response.DebugInformation 查看实际发送的 JSON 请求基本上就这些。NEST 封装得足够友好,只要版本对齐、认证配对、类型映射合理,日常增删改查非常直观。遇到报错优先看 response.DebugInformation 和 HTTP 状态码(比如 401=认证失败,400=DSL 错误,404=索引不存在)。