Java連線ElasticSearch

黃寶康發表於2018-02-06

新建maven工程,新增依賴

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.5.2</version>
</dependency>

啟動好ElasticSearch服務,編寫測試類。

package com.hbk.es;

import java.net.InetAddress;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class Test {

    private static String host = "192.168.8.133";
    private static int port = 9200;

    public static void main(String[] args) throws Exception {
        @SuppressWarnings({ "resource", "unchecked" })
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
        System.out.println(client);
        client.close();
    }
}

輸出:

ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
org.elasticsearch.transport.client.PreBuiltTransportClient@6105f8a3

報Error是因為沒有加log4j日誌包,沒事!

相關文章