Last active
May 28, 2020 13:37
-
-
Save luizgpsantos/877f2c4fa0f08de0d5096d84243eef5f to your computer and use it in GitHub Desktop.
Elasticsearch Rest Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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