【问题标题】:How to search via Json in elastic search using spring resttemplate in android如何在 android 中使用 spring resttemplate 在弹性搜索中通过 Json 进行搜索
【发布时间】:2017-07-03 14:45:36
【问题描述】:

您好,我正在尝试使用 spring RestTemplate 在弹性搜索中搜索数据。 ElasticSearch 有用户名和密码,我想通过 json 搜索。

我为此编写了代码,但没有得到任何结果或异常。这是我有生以来第一次这样做,如果其中有一些愚蠢的错误,我深表歉意。

@Override
    protected List<JobPosts> doInBackground(Object[] objects) {
        List list = null;

        try {

            SearchForm searchForms = (SearchForm) objects[0];




            String plainCreds = "******:********";

            final String url = "*******";
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

            HttpEntity<String> request = new HttpEntity<>(searchJson, headers);
            Log.d("location", "before exchange");
            ResponseEntity<JobPosts[]> response = restTemplate.exchange(url, HttpMethod.GET, request, JobPosts[].class);
            JobPosts[] jobPosts = response.getBody();

            Log.d("location", "after exchange");
            list = Arrays.asList(jobPosts);


        } catch (Exception e) {
            Log.d("location", e.getMessage());
        }

【问题讨论】:

  • 可能使用 cURL 或 REST 客户端插件(Postman、高级 REST 客户端...)在深入研究代码之前验证您是否可以访问 Elasticsearch。 localhost:9200 是您的基本 URL。但我建议使用评论中提到的 ES Java API。我也从 Spring 数据切换到原生 API 以获得更好的支持

标签: android elasticsearch spring-restdocs


【解决方案1】:

与其他关系型数据库不同,您不需要 Spring RestTemplate 来查询弹性数据库。 ElasticSearch 带有内置的 Java API 库。您可以直接使用这些函数来创建查询并获取结果。

查看此链接。它有关于如何使用 API 的文档。

Elastic Search Java API 5.1

【讨论】:

    【解决方案2】:

    我建议使用 Tanay 提到的 ES Java API

    这样设置你的连接

    //Create the ES clien
    org.elasticsearch.client.Client client;
    
    //Setup the connection. Make sure you use port 9300 and not 9200 here.
    client = new PreBuiltTransportClient(Settings.EMPTY)
                        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), "9300"));
    
    //Interact with your index, for example getting an object by its ID
    GetResponse response = client.prepareGet("index", "type", "id")
        .setOperationThreaded(false)
        .get();
    
    //Close the connection
    client.close();
    

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多