2016-09-30 70 views
0

我正在关注Java客户端上的ElasticSearch文档。我已经启动了ElasticSearch,并且可以使用Rest API与它进行交互。我想使用的Java客户端,到目前为止,我有一个主这样的:如何使用Java传输客户端连接到ElasticSearch?

public class TestElastic { 

public static void main(String[] args) { 
    try{ 
     TransportClient client = TransportClient.builder().build() 
     .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); 
     JSONObject place = new JSONObject(); 
     place.put("name", "AAAAA"); 
     IndexResponse response = client.prepareIndex("my_database", "places", "1") 
       .setSource(place) 
       .get(); 
     System.out.println(response.toString()); 
     // Index name 
     String _index = response.getIndex(); 
     System.out.println(_index); 
     // Type name 
     String _type = response.getType(); 
     System.out.println(_type); 
     // Document ID (generated or not) 
     String _id = response.getId(); 
     System.out.println(_id); 
     // Version (if it's the first time you index this document, you will get: 1) 
     long _version = response.getVersion(); 
     System.out.println(_version); 
     // isCreated() is true if the document is a new one, false if it has been updated 
     boolean created = response.isCreated(); 
     System.out.println(created); 
     client.close(); 
    }catch (Exception ex){ 
     ex.printStackTrace(); 
    } 
} 

}

在Java日志中我可以看到,有一个与127.0.0.1:9300的连接。但在“准备索引”命令后,我没有看到任何错误,也没有打印任何内容(我有一些系统输出命令)。在ElasticSearch日志中也没有任何关系。当我使用Rest API创建索引时,我可以在日志中看到这一点。

+1

你可以在catch块中添加'ex.printStackTrace();',这样我们可以看到是否有异常?你默默吞咽;-) – Val

+0

你是对的。我怎么会错过这个? –

回答

0

好吧,正如@Val提到的,我忘记了打印错误。问题是JSONObject不是ElasticSearch想要的格式。 Map和HashMap是可以接受的。

相关问题