public static void main(String[] args) throws IOException { Settings settings = ImmutableSettings.settingsBuilder() .put("cluster.name", "foxzen") .put("node.name", "yu").build(); Client client = new TransportClient(settings) .addTransportAddress(new InetSocketTransportAddress("XXX.XXX.XXX.XXX", 9200)); // XXX is my server's ip address IndexResponse response = client.prepareIndex("twitter", "tweet") .setSource(XContentFactory.jsonBuilder() .startObject() .field("productId", "1") .field("productName", "XXX").endObject()).execute().actionGet(); System.out.println(response.getIndex()); System.out.println(response.getType()); System.out.println(response.getVersion()); client.close(); }
我从计算机访问服务器
curl -get http://XXX.XXX.XXX.XXX:9200/
得到这个
{ "status" : 200, "name" : "yu", "version" : { "number" : "1.1.0", "build_hash" : "2181e113dea80b4a9e31e58e9686658a2d46e363", "build_timestamp" : "2014-03-25T15:59:51Z", "build_snapshot" : false, "lucene_version" : "4.7" }, "tagline" : "You Know, for Search" }
为什么使用Java API会出错?
编辑
有集群和节点部分的配置 elasticsearch.yml
elasticsearch.yml
################################### Cluster ################################### # Cluster name identifies your cluster for auto-discovery. If you're running # multiple clusters on the same network, make sure you're using unique names. # cluster.name: foxzen #################################### Node ##################################### # Node names are generated dynamically on startup, so you're relieved # from configuring them manually. You can tie this node to a specific name: # node.name: yu
一些建议:
1-使用端口9300。[9300-9400]用于节点到节点通信,[9200-9300]用于HTTP通信。
2-确保您使用的Java API的版本与服务器上运行的elasticsearch的版本匹配。
3-确保集群名称为foxzen(检查服务器上的elasticsearch.yml)。
foxzen
4-删除put("node.name", "yu"),因为您正在使用TransportClient,yu所以您不会作为节点加入群集,即使您看起来像是服务器节点也已命名,因此无论如何都希望使用其他节点名称。
put("node.name", "yu")
TransportClient
yu