ElasticSearch 测试连接工具(TestConnection)

本文介绍了一种在Elasticsearch中测试服务器连接状态的方法。由于0.90.x版本后,Elasticsearch移除了connectedNodes API,作者提供了一个Java工具类来替代。该工具类通过查询集群节点信息来验证连接的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

截止到0.90.x的版本,Elasticsearch已经将connectedNodes从api中去掉,具体代替的方法是什么呢?也没有找到相关的说明。

因此决定自己手工写一个工具类。其实,我们只有通过API去执行一个方法,就可以测试连接是否正常。测试的方法选定为获得集群node的信息。测试代码:

Java代码
  1. import java.util.Map;  

  2. import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;  

  3. import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest;  

  4. import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;  

  5. import org.elasticsearch.client.Client;  

  6.  

  7. import com.donlianli.es.ESUtils;  

  8. /**

  9. * @author donlianli@126.com

  10. * 测试服务器的可用状态

  11. */  

  12. public class TestConnection {  

  13.    /**

  14.     * 测试ES可用连接数方法

  15.     * 同时也也可以用以校验ES是否可以连接上

  16.     */  

  17.    public static void main(String[] args) {  

  18.        //通过transport方式连接哦,否则没有意义了  

  19.        Client client = ESUtils.getClient();  

  20.        try{  

  21.            NodesInfoResponse response = client.admin().cluster()  

  22.                    //超时时间设置为半分钟  

  23.                    .nodesInfo(new NodesInfoRequest().timeout("30")).actionGet();  

  24.            Map<String,NodeInfo> nodesMap = response.getNodesMap();  

  25.            //打印节点信息  

  26.            for(Map.Entry<String, NodeInfo> entry : nodesMap.entrySet()){  

  27.                System.out.println(entry.getKey() + ":" + entry.getValue().getServiceAttributes()) ;  

  28.            }  

  29.        }  

  30.        catch(Exception e){  

  31.            e.printStackTrace();  

  32.            System.out.println("无法连接到Elasticsearch");  

  33.        }  

  34.    }  

  35. }  

### Python连接Elasticsearch示例代码及教程 #### 安装依赖 为了能够顺利操作Elasticsearch,需先通过pip工具安装`elasticsearch`包。这一步骤确保了后续程序能调用必要的API来管理索引以及执行各种命令。 ```bash pip install elasticsearch ``` 此命令会下载并安装最新版本的`elasticsearch-py`库[^1]。 #### 创建Elasticsearch客户端实例 建立与Elasticsearch集群之间的通信链路是至关重要的第一步。下面展示了如何初始化一个简单的客户端对象: ```python from elasticsearch import Elasticsearch es_client = Elasticsearch( "http://localhost:9200", # 替换为实际地址 request_timeout=30 # 设置请求超时时间 ) if not es_client.ping(): raise ValueError("Connection failed") print('Connected to ES!') ``` 上述脚本尝试连接至本地运行的Elasticsearch服务,并验证连通性;如果成功,则打印确认消息[^2]。 #### 删除已有索引 有时需要清理旧数据以便于重新构建新的结构化存储空间。这里提供了一种方法用于移除指定名称的索引: ```python index_name = 'test_index' if es_client.indices.exists(index=index_name): response = es_client.indices.delete(index=index_name) print(f"Index '{index_name}' deleted successfully.") else: print(f"Index '{index_name}' does not exist.") ``` 这段代码首先检查目标索引是否存在,存在则予以删除,并给出相应的反馈信息。 #### 新建索引配置映射关系 定义好文档类型的字段及其属性对于优化检索性能至关重要。接下来展示的是创建新索引的同时设置其内部结构的方式: ```python settings_and_mappings = { "settings": { "number_of_shards": 1, "number_of_replicas": 0 }, "mappings": { "properties": { "title": {"type": "text"}, "content": {"type": "text"} } } } response = es_client.indices.create( index=index_name, body=settings_and_mappings) print(response.get('acknowledged', False)) ``` 此处设定了单一分片无副本模式下的两个文本型字段作为例子说明。 #### 测试中文分词功能 最后介绍一种简单的方式来检验所使用的分析器能否正确处理特定语言的文字串。假设已经加载了一个适合汉语环境的插件,那么可以通过如下方式来进行初步测试: ```python text_to_analyze = "这是一个测试字符串" analysis_result = es_client.indices.analyze( index=index_name, body={ "analyzer": "ik_max_word", "text": text_to_analyze }) tokens = [token['token'] for token in analysis_result['tokens']] print(tokens) ``` 以上过程利用内置或自定义好的IK Analyzer实现了对给定语句的有效分割。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值