有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

elasticsearch尝试访问Elastic Search get时使用java获取空响应

遵循Elastic Search的文档,我们能够为其API设置Java环境。 但当尝试从名为twitter的索引访问时,在名为tweet的类型下,id值为1,响应为空,控制台中没有错误

上面的代码

Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch").build();

        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

        GetResponse response = client.prepareGet("twitter", "tweet", "2").get();
        System.out.println(response.getFields());

        client.close();

Kibana控制台上的数据

{
        "_index": "twitter",
        "_type": "tweet",
        "_id": "2",
        "_score": 1,
        "_source": {
          "user": "Rahul",
          "post_date": "2009-11-15T14:12:12",
          "message": "trying out Elasticsearch"
        }
      },
      {
        "_index": "twitter",
        "_type": "tweet",
        "_id": "1",
        "_score": 1,
        "_source": {
          "user": "kimchy",
          "post_date": "2009-11-15T14:12:12",
          "message": "trying out Elasticsearch"
        }
      }

共 (2) 个答案

  1. # 1 楼答案

    请尝试一下这样的东西,希望能有所帮助

    RestClient restClient = RestClient.builder(
                    new HttpHost("localhost", 9200, "http")).build();
    
            Response response = restClient.performRequest("GET", "/twitter/_search",
                   Collections.singletonMap("pretty", "true"));
    
    
    /*
            JsonObject user = new JsonObject();
            user.addProperty("user","Yash");
            user.addProperty("post_date","2009-11-15T14:12:12");
            user.addProperty("message","Checking json");
    
            HttpEntity entity = new NStringEntity(user.toString());
    
            Response indexResponse = restClient.performRequest(
                    "PUT",
                    "/twitter/tweet/3",
                    Collections.<String, String>emptyMap(),
                    entity);
    */
    
    
    
    
    
            System.out.println(EntityUtils.toString(response.getEntity()));
    
            restClient.close();
    
  2. # 2 楼答案

    确保您使用的是HTTP,而不是HTTPs——如果您发出简单的纯文本HTTP请求,服务器可能会挂断您的连接