How to insert document into ElasticSearch using RestHighLevelClient in Java Spring Boot

I am developing a Spring Boot program that use RestHighLevelClient to insert document into ElasticSearch. Now I have built the configuration for the client, however, I am not sure how to insert/index. The documentation on ElasticSearch seems confusing to me..

Here is the piece of code I tried so far:

@KafkaListener(topics = "${kafka.topic}",groupId = "test")
public void receive(String message) {

    LOGGER.info(message);
    insertData(message);
    latch.countDown();
}

private void insertData(String message){
    IndexRequest request = new IndexRequest(
            "fx-rate",
            "_doc",
            "1");
    request.source(message, XContentType.JSON);
}

1 answer

  • answered 2018-03-13 20:27 Egor Kravchenko

    A RestHighLevelClient instance needs a REST low-level client builder to be built as follows:

       RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost("localhost", 9200, "http"),
                    new HttpHost("localhost", 9201, "http")));
    

    Create an index (if it not exist)

    CreateIndexRequest request = new CreateIndexRequest("twitter");

    Update document:

    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    {
        builder.field("updated", new Date());
        builder.field("reason", "daily update");
    }
    builder.endObject();
    UpdateRequest request = new UpdateRequest("posts", "doc", "1")
            .doc(builder);
    

    Use your client for send request.

    P.S. es high level client