How to search via Json in elastic search using spring resttemplate in android
Asked Answered
N

2

0

Hi i am trying to search data in elastic search using spring RestTemplate. ElasticSearch have user name and password and i want to search via json.

I wrote code for this but i am not getting any result or exception. I am doing this for the first time in my life so sorry if there is some silly mistake in it.

@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());
        }
Nipa answered 15/2, 2017 at 4:45 Comment(1)
Maybe using cURL or a REST client plugin (Postman, advanced REST client, ...) to validate if you can reach Elasticsearch before diving in the code. localhost:9200 is your base URL. But I would recommend using the ES Java API as mentioned in the comment. I've switched from Spring data to the native API as well for better supportEsquire
D
1

Unlike other Relational Databases, you don't need Spring RestTemplate to query the elastic database. ElasticSearch comes with inbuilt Java API library. You directly use those functions to create your query and get the results.

Checkout this Link. It has the documentation about how to use the API.

Elastic Search Java API 5.1

Dashed answered 15/2, 2017 at 11:1 Comment(0)
E
0

I would recommend Using the ES Java API as mentioned by Tanay.

Set up your connection like this

//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();
Esquire answered 7/3, 2017 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.