Hackerss.com

hackerss
hackerss

Posted on

Java Connect to elasticsearch


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class ElasticSearch {

    public static void main(String[] args) throws UnknownHostException {

        // Connect to elasticsearch
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch").build();
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

        // Search for all documents in the index
        SearchResponse response = client.prepareSearch("twitter")
                .setTypes("tweet")
                .setQuery(QueryBuilders.matchAllQuery())
                .setFrom(0).setSize(60).setExplain(true)
                .execute()
                .actionGet();

        // Get the results
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        for (SearchHit hit : response.getHits().getHits()) {
            results.add(hit.getSource());
        }

        // Print the results
        System.out.println(results);

        // Close the connection
        client.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)