大数据技术之Elasticsearch-Java API操作(一)API基本操作

 

获取Transport Client

(1)ElasticSearch服务默认端口9300。

(2)Web管理平台端口9200。

//org.elasticsearch.transport.client.PreBuiltTransportClient@4bff2185

//org.elasticsearch.transport.client.PreBuiltTransportClient@6f099cef

private TransportClient client;

 

@SuppressWarnings("unchecked")

@Before

public void getClient() throws Exception {

 

// 1 设置连接的集群名称

Settings settings = Settings.builder().put("cluster.name", "my-application").build();

 

// 2 连接集群

client = new PreBuiltTransportClient(settings);

client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop102"), 9300));

 

// 3 打印集群名称

System.out.println(client.toString());

}

(3)显示log4j2报错,在resource目录下创建一个文件命名为log4j2.xml并添加如下内容

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

 

*******自己操作******

Java代码:

// 对ES的操作都是通过client
    private TransportClient client;

    // 注意:加注解才能运行
    @SuppressWarnings("unchecked")
    @Before
    // @Before 以后在操作ES的时候首先获取连接-初始化Client
    // 获取连接-初始化Client
    public void getClient() throws Exception {
        // 1.设置连接集群的名称
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();
        // 2.连接集群
        client = new PreBuiltTransportClient(settings);
        // IP,client-客户机操作ES的端口号
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.212.111"), 9300));
    }

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3