使用NEST操作Elasticsearch报错:连接被主动拒绝,求技术支持
问题解决:Elasticsearch NEST客户端连接失败及索引不一致问题
错误核心原因
- Elasticsearch服务未启动/端口不匹配:调试信息中的
System.Net.Sockets.SocketException (10061): 无法建立连接,因为目标机器主动拒绝了连接,说明客户端无法访问http://127.0.0.1:9200,大概率是本地Elasticsearch服务未启动,或端口配置与代码不符。 - 索引配置不一致:代码中默认索引设置为
foo,但实际创建的索引是indexName,调用IndexDocument(doc)时会使用默认索引foo,而该索引并未创建,导致后续报错。
修复步骤
验证Elasticsearch服务状态:
- 打开浏览器访问
http://127.0.0.1:9200,若返回包含Elasticsearch版本信息的JSON内容,说明服务正常运行;若无法访问,需启动服务:- Windows:打开Elasticsearch安装目录下的
bin文件夹,运行elasticsearch.bat - Linux/macOS:在终端执行Elasticsearch安装目录下的
bin/elasticsearch命令
- Windows:打开Elasticsearch安装目录下的
- 若服务端口不是9200,需同步修改代码中的连接URI。
- 打开浏览器访问
修正索引配置不一致问题:
方案一:将默认索引改为实际创建的indexName,确保IndexDocument使用正确索引:var settings = new ConnectionSettings(new Uri("http://127.0.0.1:9200")) .DefaultIndex("indexName");方案二:调用
Index方法时显式指定索引,无需修改默认索引:var indexResponse = client.Index(doc, i => i.Index(indexName));可选:启用调试日志:
在ConnectionSettings中添加DisableDirectStreaming(),可在报错时查看完整请求/响应内容,便于后续调试:var settings = new ConnectionSettings(new Uri("http://127.0.0.1:9200")) .DefaultIndex("indexName") .DisableDirectStreaming();
修正后的完整代码
Program类
using Nest; using System; class Program { static void Main(string[] args) { var settings = new ConnectionSettings(new Uri("http://127.0.0.1:9200")) .DefaultIndex("indexName") .DisableDirectStreaming(); var client = new ElasticClient(settings); var indexName = "indexName"; if (client.Indices.Exists(indexName).Exists) { client.Indices.Delete(indexName); } var createIndexResponse = client.Indices.Create(indexName, c => c .Settings(s => s .Analysis(a => a .Analyzers(an => an .Custom("my_analyzer", ca => ca .Tokenizer("standard") .CharFilters("html_strip") .Filters("lowercase") ) ) ) ) .Mappings(m => m .Map<Document>(mp => mp .AutoMap() .Properties(p => p .Text(t => t .Name(n => n.Title) .Analyzer("my_analyzer") ) .Text(t => t .Name(n => n.Content) .Analyzer("my_analyzer") ) ) ) ) ); if (!createIndexResponse.IsValid) { Console.WriteLine($"索引创建失败: {createIndexResponse.DebugInformation}"); Console.ReadKey(); return; } var doc = new Document { Title = "Friends are friendlier friendlies that are friendly and classify the friendly classification class.", Content = "Flowery flowers flow through following the flower flows." }; var indexResponse = client.IndexDocument(doc); if (indexResponse.IsValid) { Console.WriteLine($"文档索引成功,结果: {indexResponse.Result}"); } else { Console.WriteLine($"文档索引失败: {indexResponse.DebugInformation}"); } Console.ReadKey(); } }
Document类
class Document { public string Title { get; set; } public string Content { get; set; } }
内容的提问来源于stack exchange,提问作者Eric Aime Tchatchoua
相关产品推荐
相关产品推荐

