Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save luizgpsantos/877f2c4fa0f08de0d5096d84243eef5f to your computer and use it in GitHub Desktop.
Save luizgpsantos/877f2c4fa0f08de0d5096d84243eef5f to your computer and use it in GitHub Desktop.
Elasticsearch Rest Client
package test;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
public class SimpleOperationsElasticsearchRestClient {
private RestClient client;
public RestClient getClient() {
return client;
}
public SimpleOperationsElasticsearchRestClient() {
client = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
}
public Response indexDocument(String index, String type, String id, String json) throws IOException {
Map<String, String> params = Collections.emptyMap();
HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);
Response response = getClient().performRequest("PUT", "/posts/doc/1", params, entity);
return response;
}
public static void main(String[] args) {
SimpleOperationsElasticsearchRestClient example = new SimpleOperationsElasticsearchRestClient();
String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\","
+ "\"message\":\"trying out Elasticsearch\"" + "}";
try {
Response response = example.indexDocument("posts", "doc", "1", json);
System.out.println(response.toString());
example.getClient().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment