C#怎么連接Elaticearch NEST客戶端使用方法
最常用且官方推薦的方式是使用 NEST 客戶端,需匹配 Elasticsearch 服務版本安裝對應 NuGet 包,通過 ElasticClient 配置連接、索引文檔和執行查詢,支持強類型、LINQ、自動序列化與生產級特性。

用 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 配置連接信息:
1 2 3 4 | 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] 等特性控制字段類型):

node-connect診斷Android、iOS及macOS配套應用的OpenClaw節點連接與配對故障,適用于二維碼/設置碼/手動連接失敗或本地Wi-Fi問題時。
下載 1 2 3 4 5 6 7 | public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public DateTime CreatedAt { get; set; }
}
|
插入或替換文檔:
1 2 3 | 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 獲取:
1 2 | var getResponse = await client.GetAsync<Product>(1, idx => idx.Index("my-products"));
if (getResponse.Found) Console.WriteLine(getResponse.Source.Name);
|
條件搜索(比如價格大于 500 的商品):
1 2 3 4 5 6 7 8 9 10 | 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>,記得檢查 .IsValid 和 .ServerError - 復雜查詢可用
Bool() 組合 must/should/must_not,支持分頁(.From().Size())、排序、高亮等 - 調試時可打印
response.DebugInformation 查看實際發送的 JSON 請求
基本上就這些。NEST 封裝得足夠友好,只要版本對齊、認證配對、類型映射合理,日常增刪改查非常直觀。遇到報錯優先看 response.DebugInformation 和 HTTP 狀態碼(比如 401=認證失敗,400=DSL 錯誤,404=索引不存在)。
“C#怎么連接Elaticearch NEST客戶端使用方法” 的相關文章