欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Elasticsearch 5.X Java API 创建客户端

程序员文章站 2022-07-05 14:19:43
...
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.get.GetResponse;
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 CreateClient
{
    public static void main(String[] args)
    {
        // elasticsearch为集群名称,根据elasticsearch.yml中cluster.name设置,默认elasticsearch
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        TransportClient client = null;
        try
        {
            client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        // index:索引,type:类型,id:文档id
        GetResponse response = client.prepareGet("hbdss", "patient", "1").execute().actionGet();
        System.out.println(response.getSourceAsString());
        client.close();
    }
}