Using Elasticsearch Java High Level REST Client
Installation
Add dependency to your pom.xml ;
<dependency> <groupid>org.elasticsearch.client</groupid> <artifactid>elasticsearch-rest-high-level-client</artifactid> <version>6.2.4</version> </dependency>
Update application dependencies with maven;
$mvn clean install
Create Client
RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("site:api-key@xyz.searchly.com", 443, "https")));
Index Creation
CreateIndexRequest request = new CreateIndexRequest("articles"); CreateIndexResponse createIndexResponse = client.indices().create(request);
Search
Index an article;
IndexRequest request = new IndexRequest( "articles", "doc", "1"); String jsonString = "{" + "\"author\":\"john ronald reuel tolkien\"," + "\"content\":\"the lord of the rings is an epic high fantasy novel\"," + "}"; request.source(jsonString, XContentType.JSON); IndexResponse indexResponse = client.index(request);
You can search indexed article as:
SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(new MatchQueryBuilder("content", "lord")); searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = client.search(searchRequest);
Useful Resources
Java Rest client has very detailed documentation at at Github.
Using Jest for Elasticsearch version below 6
A sample Java application can be found on GitHub https://github.com/searchly/searchly-java-sample.
Installation
Documentation targets Java client Jest for Elasticsearch.
Add Jest dependency to your pom.xml ;
<dependency> <groupid>io.searchbox</groupid> <artifactid>jest</artifactid> <version>0.1.6</version> </dependency>
Update application dependencies with maven;
$mvn clean install
Create Client
// construct a new jest client according to configuration via factory Jestclientfactory factory = new Jestclientfactory(); factory.sethttpclientconfig(new HttpClientConfig .builder("https://site:api-key@xyz.searchly.com:443") .multithreaded(true) .build()); jestclient client = factory.getobject();
Index Creation
client.execute(new CreateIndex.Builder("articles").build());
Search
Index an article;
Article source = new Article(); source.setauthor("john ronald reuel tolkien"); source.setcontent("the lord of the rings is an epic high fantasy novel"); Index index = new Index.Builder(source).index("articles").type("article").build(); client.execute(index);
You can search indexed article as:
String query = "{ \"query\": { \"match\" : { \"content\" : \"lord\" } } }"; Search search = (search) new search.builder(query) .addindex("articles") .addtype("article") .build(); Jestresult result = client.execute(search);
Useful Resources
Jest client has very detailed documentation at at Github.