4

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);
}
0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

If you know how to insert documents through API then this way will much more easy for you to do anything similar API (DELETE,POST,PUT...) First, you will need RestHighLevelClient and all you have to do

String index = "/s3-upload-2022.10.04/_doc/2"; <-- Your path
Request request = new Request("POST", index);  <-- Your method
request.setJsonEntity(
          "{ \"message\": \" example add insert\" }"  <-- Your request body
);

client.getLowLevelClient().performRequest(request); <-- Run Action

This will execute like how API does.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.