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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM