Skip to content

Feature/issues/2334/create elastic spring app #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions spring-elastic/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### VS Code ###
.vscode/
19 changes: 19 additions & 0 deletions spring-elastic/.mvn/wrapper/maven-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
145 changes: 145 additions & 0 deletions spring-elastic/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# Spring Boot Elasticsearch Example

This project is a simple Spring Boot application that demonstrates how to integrate with Elasticsearch using the Java High-Level REST Client. It provides REST endpoints to create and search books in an Elasticsearch index.

## Prerequisites

- **Java Development Kit (JDK) 8 or higher**
- **Maven** for building the project
- **Docker** for running Elasticsearch
- An API client like **Postman** or **cURL** for testing endpoints

## Setting Up Elasticsearch with Docker

To run Elasticsearch, we'll use Docker to pull and run the official Elasticsearch image.

Execute the following command in your terminal:

```bash
docker run -d \
-p 9200:9200 \
-p 9300:9300 \
--name elasticsearch \
-e "discovery.type=single-node" \
-e "xpack.security.enabled=false" \
docker.elastic.co/elasticsearch/elasticsearch:8.15.2
```

## Explanation of the Docker Command:

- `-d`: Run the container in detached mode (in the background).
- `-p 9200:9200`: Map port 9200 of the host to port 9200 of the container (HTTP API).
- `-p 9300:9300`: Map port 9300 of the host to port 9300 of the container (Transport API).
- `--name elasticsearch`: Assign the name "elasticsearch" to the container.
- `-e "discovery.type=single-node"`: Run Elasticsearch in single-node mode.
- `-e "xpack.security.enabled=false"`: Disable X-Pack security features for simplicity. !!! Not recommended for production
- `docker.elastic.co/elasticsearch/elasticsearch:8.15.2`: The Docker image to use.

### Verify Elasticsearch is Running:

After running the Docker command, verify that Elasticsearch is running by accessing [http://localhost:9200](http://localhost:9200) in your browser or using `curl`:

```bash
curl http://localhost:9200
```

You should receive a JSON response with cluster information.

Running the Spring Boot Application
1. Clone the Repository

```bash
git clone https://github.com/yourusername/your-repo-name.git
cd your-repo-name
```

2. Configure Application Properties
Ensure that your application.properties file is correctly set up. It should be located in src/main/resources/ and contain the following properties:

```bash
spring.application.name=spring-elastic
server.port=8081

spring.elasticsearch.url=localhost
spring.elasticsearch.port=9200

# Credentials are optional if security is disabled
spring.elasticsearch.username=
spring.elasticsearch.password=
```
3. Build the Project
Use Maven to build the project:

```bash
mvn clean install
```

4. Run the Application
You can run the application using Maven:


```bash
mvn spring-boot:run
```

Or run the generated JAR file:

```bash
java -jar target/your-app-name.jar
```
The application will start on port 8081.

Project Structure
- Controller
BookController: Handles HTTP requests for creating and searching books.
- Model
Book: Represents the book entity stored in Elasticsearch.
- Client
BookElasticsearchClient: Manages the connection to Elasticsearch.
- Service
BookElasticsearchService: Contains business logic for interacting with Elasticsearch.
Endpoints
1. Create a Book
- URL: /book/create
- Method: POST
- Description: Creates a new book in the Elasticsearch index.
- Request Body:

```bash
{
"id": "1",
"name": "Elasticsearch Basics",
"description": "An introductory guide to Elasticsearch.",
"price": 29.99
}
```
Sample cURL Request:

```bash
curl -X POST \
http://localhost:8081/book/create \
-H 'Content-Type: application/json' \
-d '{
"id": "1",
"name": "Elasticsearch Basics",
"description": "An introductory guide to Elasticsearch.",
"price": 29.99
}'
```

2. Find Books by Name
- URL: /book/find_by_name
- Method: GET
- Description: Searches for books by name in the Elasticsearch index.
- Query Parameter:
- name: The name or partial name of the book to search for.
```bash
curl -X GET "http://localhost:8081/book/find_by_name?name=Elasticsearch"
```

### Conclusion
You have successfully set up an Elasticsearch instance using Docker and run a Spring Boot application that interacts with it. This application demonstrates basic CRUD operations with Elasticsearch, providing a foundation for more complex integrations.

Feel free to extend this application by adding more features like update and delete operations, or by integrating authentication and security features.

Note: In a production environment, you should enable security features in Elasticsearch and handle credentials appropriately.
61 changes: 61 additions & 0 deletions spring-elastic/keploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
path: ""
appId: 0
appName: spring-elastic
command: mvn spring-boot:run
templatize:
testSets: []
port: 0
dnsPort: 26789
proxyPort: 16789
debug: false
disableTele: false
disableANSI: false
containerName: ""
networkName: ""
buildDelay: 30
test:
selectedTests: {}
globalNoise:
global: {}
test-sets: {}
delay: 5
host: ""
port: 0
apiTimeout: 5
skipCoverage: false
coverageReportPath: ""
ignoreOrdering: true
mongoPassword: default@123
language: ""
removeUnusedMocks: false
fallBackOnMiss: false
jacocoAgentPath: ""
basePath: ""
mocking: true
ignoredTests: {}
disableLineCoverage: false
disableMockUpload: true
useLocalMock: false
updateTemplate: false
record:
filters: []
recordTimer: 0s
configPath: ""
bypassRules: []
generateGithubActions: false
keployContainer: keploy-v2
keployNetwork: keploy-network
cmdType: native
contract:
services: []
tests: []
path: ""
download: false
generate: false
driven: consumer
mappings:
servicesMapping: {}
self: ""
inCi: false

# Visit [https://keploy.io/docs/running-keploy/configuration-file/] to learn about using keploy through configration file.
1 change: 1 addition & 0 deletions spring-elastic/keploy/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/reports/
75 changes: 75 additions & 0 deletions spring-elastic/keploy/test-set-1/mocks.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
version: api.keploy.io/v1beta1
kind: Http
name: mock-0
spec:
metadata:
name: Http
operation: POST
type: HTTP_CLIENT
req:
method: POST
proto_major: 1
proto_minor: 1
url: /books/_search?typed_keys=true
url_params:
typed_keys: "true"
header:
Accept: application/vnd.elasticsearch+json; compatible-with=8
Connection: Keep-Alive
Content-Type: application/vnd.elasticsearch+json; compatible-with=8
User-Agent: elastic-java/8.11.0 (Java/21.0.4)
X-Elastic-Client-Meta: es=8.11.0,jv=21,t=8.11.0,hl=2,hc=4.1.5
body: '{"query":{"match":{"name":{"query":"Great"}}}}'
timestamp: 0001-01-01T00:00:00Z
resp:
status_code: 200
header:
Content-Length: "385"
Content-Type: application/vnd.elasticsearch+json;compatible-with=8
X-Elastic-Product: Elasticsearch
body: '{"took":85,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":0.6407243,"hits":[{"_index":"books","_id":"1","_score":0.6407243,"_source":{"id":"1","name":"The Great Gatsby","description":"A novel set in the Jazz Age that tells the story of Jay Gatsby and his love for Daisy Buchanan.","price":30.0}}]}}'
status_message: ""
proto_major: 0
proto_minor: 0
timestamp: 0001-01-01T00:00:00Z
objects: []
created: 1729798124
reqTimestampMock: 2024-10-24T21:28:44.059763186+02:00
resTimestampMock: 2024-10-24T21:28:44.059763186+02:00
---
version: api.keploy.io/v1beta1
kind: Http
name: mock-1
spec:
metadata:
name: Http
operation: PUT
type: HTTP_CLIENT
req:
method: PUT
proto_major: 1
proto_minor: 1
url: /books/_doc/2
header:
Accept: application/vnd.elasticsearch+json; compatible-with=8
Connection: Keep-Alive
Content-Type: application/vnd.elasticsearch+json; compatible-with=8
User-Agent: elastic-java/8.11.0 (Java/21.0.4)
X-Elastic-Client-Meta: es=8.11.0,jv=21,t=8.11.0,hl=2,hc=4.1.5
body: '{"id":"2","name":"Harry Potter","description":"A magical journey of a young wizard, Harry Potter, as he navigates his adventures in the wizarding world and faces his ultimate enemy, Lord Voldemort.","price":50.0}'
timestamp: 0001-01-01T00:00:00Z
resp:
status_code: 200
header:
Content-Length: "138"
Content-Type: application/vnd.elasticsearch+json;compatible-with=8
X-Elastic-Product: Elasticsearch
body: '{"_index":"books","_id":"2","_version":2,"result":"updated","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":2,"_primary_term":8}'
status_message: ""
proto_major: 0
proto_minor: 0
timestamp: 0001-01-01T00:00:00Z
objects: []
created: 1729798145
reqTimestampMock: 2024-10-24T21:29:05.714170448+02:00
resTimestampMock: 2024-10-24T21:29:05.714170448+02:00
47 changes: 47 additions & 0 deletions spring-elastic/keploy/test-set-1/tests/test-1.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
version: api.keploy.io/v1beta1
kind: Http
name: test-1
spec:
metadata: {}
req:
method: GET
proto_major: 1
proto_minor: 1
url: http://localhost:8081/book/find_by_name?name=Great
url_params:
name: Great
header:
Accept: '*/*'
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Host: localhost:8081
Postman-Token: 533f7ecd-38bc-432b-8288-4c65ac3feffd
User-Agent: PostmanRuntime/7.26.8
body: ""
timestamp: 2024-10-24T21:28:43.206142562+02:00
resp:
status_code: 200
header:
Connection: keep-alive
Content-Type: application/json
Date: Thu, 24 Oct 2024 19:28:44 GMT
Keep-Alive: timeout=60
body: '[{"id":"1","name":"The Great Gatsby","description":"A novel set in the Jazz Age that tells the story of Jay Gatsby and his love for Daisy Buchanan.","price":30.0}]'
status_message: OK
proto_major: 0
proto_minor: 0
timestamp: 2024-10-24T21:28:46.844302549+02:00
objects: []
assertions:
noise:
header.Date: []
created: 1729798126
curl: |
curl --request GET \
--url http://localhost:8081/book/find_by_name?name=Great \
--header 'Accept-Encoding: gzip, deflate, br' \
--header 'Connection: keep-alive' \
--header 'User-Agent: PostmanRuntime/7.26.8' \
--header 'Accept: */*' \
--header 'Postman-Token: 533f7ecd-38bc-432b-8288-4c65ac3feffd' \
--header 'Host: localhost:8081' \
Loading
Loading