• Stars
    star
    115
  • Rank 305,916 (Top 7 %)
  • Language
    Java
  • Created over 11 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌐 This application illustrates and demonstrates use of ElasticSearch Java API in the backend

Build Status Codacy Badge "Docker Pulls Codacy Badge Analytics

A Demonstration of How to Use the Elasticsearch Java API

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.

What you will learn in this repository?

  • How to use Java High Level REST Client
    • How to perform Administration operations
    • Index creation
    • Mapping settings
    • How to perform CRUD operations

Initialization Java High Level REST Client

    @Bean(destroyMethod = "close")
    public RestHighLevelClient getRestClient() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost(props.getClients().getHostname(),
                props.getClients().getHttpPort(), props.getClients().getScheme())));
    }

Index creation and Shard, Replica settings with Java High Level REST Client

final GetIndexRequest request = new GetIndexRequest(props.getIndex().getName());
final boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

if (!exists) {
    
  final CreateIndexRequest indexRequest = new CreateIndexRequest(props.getIndex().getName());
  indexRequest.settings(Settings.builder()
       .put("index.number_of_shards", props.getIndex().getShard())
       .put("index.number_of_replicas", props.getIndex().getReplica())
  );

  final CreateIndexResponse createIndexResponse = 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());
  }

}

Mapping Settings

    
final PutMappingRequest mappingRequest = new PutMappingRequest(props.getIndex().getName());
final XContentBuilder builder = XContentFactory.jsonBuilder();
    
builder.startObject();
...
builder.endObject();        

mappingRequest.source(builder);
final AcknowledgedResponse putMappingResponse = 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());
}

Using SearchSourceBuilder and showing search results

sourceBuilder.query(builder);
SearchRequest searchRequest = getSearchRequest();

SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
    Document doc = gson.fromJson(hit.getSourceAsString(), Document.class);
    doc.setId(hit.getId());
    result.add(doc);
}

Using Query String with Wildcard

result = getDocuments(QueryBuilders.queryStringQuery("*" + query.toLowerCase() + "*"));

Document deletion

final DeleteRequest deleteRequest = new DeleteRequest(props.getIndex().getName(), id);
client.delete(deleteRequest, RequestOptions.DEFAULT);

How to compile?

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.

How to run?

mvn spring-boot:run

With this option, you should provide an elasticsearch server.

How to run with Docker?

sh run.sh

With this option, this application and an elasticsearch server run together.

More Repositories

1

jenkins-pipeline

πŸ“ˆ Learn how to implement container technologies with your Jenkins CI/CD workflows to make them easier to manage in this tutorial.
Java
102
star
2

kafka-with-microservices

This repository is a tutorial for JUG Istanbul's Apache Kafka meetup that showing how Apache Kafka can be used in inter-microservices communication
Java
39
star
3

ApacheShiro

πŸ”‘ Using Apache Shiro JDBC Realm with MySQL Database
HTML
30
star
4

IntroduceToEclicpseVert.x

This repository contains the code of Vert.x examples contained in my articles published on platforms such as kodcu.com, medium, dzone. How to run each example is described in its readme file.
JavaScript
27
star
5

Java9-module-system-with-maven

Example of Java 9 module system with maven
Java
16
star
6

MongoDB

πŸ€ Using MongoDB with native Java driver and JPA via EclipseLink
Java
7
star
7

class-file-api

Class-File API is a preview API to provide a standard API for parsing, generating, and transforming Java class files
Java
7
star
8

loom-examples

This repository contains examples of Project Loom parts such as Virtual Thread, Structured Concurrency, and Scoped Values
Java
6
star
9

flight-recorder

Application monitoring with Flight Recorder
Java
6
star
10

MongoAtlas

πŸ€ This application simply exemplifies working with MongoDB Stitch via Mongo Atlas which is mongo cloud service
HTML
6
star
11

RxJavaWorkshop

This repository has some use cases related to `Rx Java` and three missions for the workshop
Java
6
star
12

SpringSecurity

πŸ”‘ Using security module with MySQL Database and Java web application
HTML
4
star
13

hibernate-search

Hibernate Search is a library that allows keeping your local Lucene indexes or ElasticSearch cluster in sync with your Database
Java
3
star
14

handy-environment

This repository contains the source code of an OpenShift S2I Builder image for Java applications
Shell
3
star
15

FacesFlow

Uses The Faces Flow
Java
2
star
16

LayrryExample

Java
2
star
17

scoped-values

The Scoped Values API allows us to store and share data for a bounded lifetime. This repository shows how you can use it.
Java
2
star
18

Java9-module-system-non-maven

Example of Java 9 module system non-maven
Java
2
star
19

finance-api

Java API and command line program to fetching foreign currency and precious metal rates from a public service
Java
2
star
20

Vert.x

A tutorial about Vert.x Mongo client
Java
1
star
21

dto-projection

This repository shows you how to use Java Records as DTO Projections
Java
1
star
22

simpleprofiler

About using custom annotations and processing them.
Java
1
star
23

jwt-rbac-quarkus

This repository is a tutorial for JUG Istanbul's How to use JWT RBAC with Quarkus meetup that showing how to verify JSON Web Tokens and provide secured access to the HTTP endpoints using Bearer Token Authorization and RBAC in Quarkus
Java
1
star
24

azure-storage-account

This repository is a tutorial about how to serve Azure Storage Resources with grant limited access using SAS in a declarative way
Java
1
star