
正文
java连接elastic search 9300
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
java连接elastic search
导入jar包:https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/_maven_repository.html
注意,使用的jar包版本尽量与所连的els版本一致
创建连接:https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/transport-client.html
查询:https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-search.html

发现两个错误:
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
错误原因:java连接els用到了log4j2,所以需要log4j2-core的依赖
解决办法:添加log4j2-core依赖
https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/_log4j_2_logger.html
NoNodeAvailableException[None of the configured nodes are available: [{#
错误原因:创建连接时需要配置cluster_name。
elasticsearch服务器的cluster_name可以在#els_home#/config/elasticsearch.yml文件中配置。

然后在java客户端程序中将
TransportClient client=new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("139.199.32.101"),9300));
改为
Settings settings=Settings.builder().put("cluster.name","production").build();
TransportClient client=new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("139.199.32.101"),9300));
JAVA客户端代码:
package com.tpot.DataDownload;import java.net.InetAddress;
import java.net.UnknownHostException;//import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
//import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws UnknownHostException
{
System.out.println( "Hello World!" ); //连接+配置
Settings settings=Settings.builder().put("cluster.name","production").build();
TransportClient client=new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("139.xxx.xxx.101"),9300)); //查询
SearchResponse response = client.prepareSearch().get();
System.out.println(response); //关闭连接
client.close();
}
}
pom.xml文件中添加的依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.3</version>
</dependency><dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>







