This repository demonstrates the use of Elasticsearch Java API via Java High Level REST Client. If you want to see the sample of the old version, please visit the oldVersion branch.
- How to use Java High Level REST Client
- How to perform Administration operations
- Index creation
- Mapping settings
- How to perform CRUD operations
@Bean(destroyMethod = "close")
publicRestHighLevelClientgetRestClient() {
returnnewRestHighLevelClient(RestClient.builder(newHttpHost(props.getClients().getHostname(),
props.getClients().getHttpPort(), props.getClients().getScheme())));
}finalGetIndexRequestrequest = newGetIndexRequest(props.getIndex().getName());
finalbooleanexists = client.indices().exists(request, RequestOptions.DEFAULT);
if (!exists) {
finalCreateIndexRequestindexRequest = newCreateIndexRequest(props.getIndex().getName());
indexRequest.settings(Settings.builder()
.put("index.number_of_shards", props.getIndex().getShard())
.put("index.number_of_replicas", props.getIndex().getReplica())
);
finalCreateIndexResponsecreateIndexResponse = client.indices().create(indexRequest, RequestOptions.DEFAULT);
if (createIndexResponse.isAcknowledged() && createIndexResponse.isShardsAcknowledged()) {
log.info("{} index created successfully", props.getIndex().getName());
} else {
log.debug("Failed to create {} index", props.getIndex().getName());
}
}finalPutMappingRequestmappingRequest = newPutMappingRequest(props.getIndex().getName());
finalXContentBuilderbuilder = XContentFactory.jsonBuilder();
builder.startObject();
...
builder.endObject(); mappingRequest.source(builder);
finalAcknowledgedResponseputMappingResponse = client.indices().putMapping(mappingRequest, RequestOptions.DEFAULT);
if (putMappingResponse.isAcknowledged()) {
log.info("Mapping of {} was successfully created", props.getIndex().getName());
} else {
log.debug("Creating mapping of {} failed", props.getIndex().getName());
}sourceBuilder.query(builder);
SearchRequestsearchRequest = getSearchRequest();
SearchResponsesearchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHitshits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHithit : searchHits) {
Documentdoc = gson.fromJson(hit.getSourceAsString(), Document.class);
doc.setId(hit.getId());
result.add(doc);
}result = getDocuments(QueryBuilders.queryStringQuery("*" + query.toLowerCase() + "*"));final DeleteRequest deleteRequest = new DeleteRequest(props.getIndex().getName(), id);
client.delete(deleteRequest, RequestOptions.DEFAULT);
mvn clean install
The docker-maven-plugin needs Docker daemon, if you don't have it you should use -Dmaven.test.skip=true -Ddocker.skip parameters.
mvn spring-boot:run
With this option, you should provide an elasticsearch server.
sh run.sh
With this option, this application and an elasticsearch server run together.
