如何使用TransportClient java代码平衡Elastic搜索节点

时间:2015-06-26 16:46:25

标签: elasticsearch

寻找专家的帮助(我是弹性搜索的新手)...有多个弹性搜索节点。

我正在使用ElasticSearch java lib来索引json文档。想知道如何处理节点平衡,是否可以从客户端处理?

--- elasticSearch传输客户端代码------

public static Client getTransportClient(String host, int port) {
     Settings settings = ImmutableSettings.settingsBuilder()
                                              .put("cluster.name", "ccw_cat_es")
                                              .put("node.name", "catsrch-pdv1-01")
                                              .build();
      return new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(host, port));
   }
   public static IndexResponse doIndex(Client client, String index, String type, String id, Map<String, Object> data) {
       return client
                    .prepareIndex(index, type, id)
                    .setSource(data)
                    .execute()
                    .actionGet();
   }
    public static void main(String[] args) {
        Client client = getTransportClient("catsrch-pdv1-01", 9200);
        String index  = "orderstatussearch";
        String type   = "osapi";
        String id     = null;       
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("OrderNumber", "444");
        data.put("PO", "123");
        data.put("WID", "ab234");

        id= "444";
        IndexResponse result = doIndex(client, index, type, id, data);
    }

public static Client getTransportClient(String host, int port) { Settings settings = ImmutableSettings.settingsBuilder() .put("cluster.name", "ccw_cat_es") .put("node.name", "catsrch-pdv1-01") .build(); return new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(host, port)); } public static IndexResponse doIndex(Client client, String index, String type, String id, Map<String, Object> data) { return client .prepareIndex(index, type, id) .setSource(data) .execute() .actionGet(); } public static void main(String[] args) { Client client = getTransportClient("catsrch-pdv1-01", 9200); String index = "orderstatussearch"; String type = "osapi"; String id = null; Map<String, Object> data = new HashMap<String, Object>(); data.put("OrderNumber", "444"); data.put("PO", "123"); data.put("WID", "ab234"); id= "444"; IndexResponse result = doIndex(client, index, type, id, data); }

1 个答案:

答案 0 :(得分:1)

TransportClient将自动使用循环策略来对其连接的节点进行负载均衡。在您的情况下,您只连接到一个节点,因此没有什么可以平衡。您可以将其他节点添加到列表中,它将适当地平衡它们。

或者,您可以通过仅应用额外设置连接到其中一个来自动“嗅探”数据节点:

Settings settings = ImmutableSettings.settingsBuilder()
    // ...
    .put("client.transport.sniff", true)
    // ...
    .build()

然后,它将针对它在群集状态中找到的所有数据节点进行循环。

这可能会导致一个问题:为什么这不是默认值?原因是,如果您有独立的客户端节点,那么它们是集群的更好代理,而不是直接与数据节点通信。对于较小的集群,这是一个完全可以接受的策略。