Getting started with Spring Boot and Elasticsearch 您所在的位置:网站首页 curl_get_data Getting started with Spring Boot and Elasticsearch

Getting started with Spring Boot and Elasticsearch

2023-04-12 07:19| 来源: 网络整理| 查看: 265

Getting started with Spring Boot and Elasticsearch

Elasticsearch N.V. (now Elastic) first published Elasticsearch in 2010, based on Apache Lucene. Elastic is a distributed open-source search and analytics engine for all forms of data, including textual, numerical, geographic, structured, and unstructured, according to its website.

REST APIs are accessible for Elasticsearch’s operations. The primary responsibilities are:

Archiving documents in an indexRetrieving those documents using sophisticated queriesProcessing the data using analytical procedures.Elasticsearch offers a straightforward interface to carry out these actions on Elasticsearch. Spring Data is an alternative to directly using the REST APIs.

You must carry out the following actions to get Spring Boot with Elasticsearch up and running:

Step 1: Installing ElasticsearchVisit the Elasticsearch download page and download the correct Elasticsearch version for your operating system (for this example, we’ll use Elasticsearch 7.15.1.)The downloaded file should be extracted from a folder on your computer.Run the following command to unzip the file and start elastic search:tar -xzf elasticsearch-7.15.1-darwin-x86_64.tar.gz -C /usr/localmv /usr/local/elasticsearch-7.15.1 /usr/local/elasticsearch./usr/local/elasticsearch/bin/elasticsearch

Note: You must run elasticsearch.bat if you are using Windows to run Elasticsearch.

Go to http://localhost:9200 in your web browser to make sure Elasticsearch is active. A JSON response with details about the Elasticsearch cluster should appear.

Step 2: Setting up a Spring Boot project with Elasticsearch

The Spring Initializr can be used to start a new Spring Boot project. You can create a new Spring Boot project using this web-based tool, complete with all the required dependencies and variables.

Open your web browser and navigate to the Spring Initializr website at https://start.spring.io/.Fill in the following details:– Project: Maven Project– Language: Java– Spring Boot: 3.0.5– Group: com.springboot– Artifact: learningElasticsearch– Packaging: Jar– Java: 11– Description: Getting started with Spring Boot & ElasticsearchClick on Add dependencies and add the following dependencies:– Spring Web– Spring Data Elasticsearch (Access + Driver)Click on Generate and download the generated zip file.You can import your produced project into your preferred IDE and begin developing your application once you have it.After all configuration, the setup should look like this.Step 3: Create necessary classesMake an Elasticsearch document representational class. For instance, if your index is called “books,” you can make a Book class that looks like this:@Document(indexName = "books")public class Book { @Id private String id;

@Field(type = FieldType.Text) private String title;

@Field(type = FieldType.Text) private String author;

@Field(type = FieldType.Date) private Date publishDate;

// getters and setters}

Note that the @Field annotations describe the mapping of each field in the index, whereas the @Document annotation indicates the name of the index to which this class maps.

Make an interface for a repository that goes beyond ElasticsearchRepository. Create a BookRepository, for instance, as follows if you wish to execute CRUD operations on the “books” index:@Repositorypublic interface BookRepository extends ElasticsearchRepository {}

Note: To conduct CRUD operations on the Elasticsearch cluster, use the ElasticsearchRepository interface.

Make a service interface that outlines the application’s business logic. One possible format for a BookService is as follows:public interface BookService { Book createBook(Book book);

Book updateBook(String id, Book book);

void deleteBook(String id);

Book getBookById(String id);}

Make a service implementation that uses the service interface’s methods. For instance, you could construct a BookServiceImpl as follows:@Servicepublic class BookServiceImpl implements BookService { @Autowired private BookRepository bookRepository;

@Override public Book createBook(Book book) { return bookRepository.save(book); }

@Override public Book updateBook(String id, Book book) { Optional existingBook = bookRepository.findById(id); if (existingBook.isPresent()) { Book savedBook = existingBook.get(); savedBook.setTitle(book.getTitle()); savedBook.setAuthor(book.getAuthor()); savedBook.setPublishDate(book.getPublishDate()); return bookRepository.save(savedBook); } else { throw new ResourceNotFoundException("Book not found with id " + id); } }

@Override public void deleteBook(String id) { Optional book = bookRepository.findById(id); if (book.isPresent()) { bookRepository.deleteById(id); } else { throw new ResourceNotFoundException("Book not found with id " + id); } }

@Override public Book getBookById(String id) { Optional book = bookRepository.findById(id); if (book.isPresent()) { return book.get(); } else { throw new ResourceNotFoundException("Book not found with id " + id); } }}

Note: This class is identified as a Spring-managed service component by the @Service tag. The service implementation implements the methods specified in the BookServiceinterface and injects the BookRepository dependency using the @Autowiredannotation. If the requested book cannot be found in the Elasticsearch cluster, the updateBook, deleteBook, and getBookById functions raise a ResourceNotFoundException.

Make a class called a controller that manages HTTP requests and maps them to the service functions. For instance, you could design a BookController in the following way:@RestController@RequestMapping("/books")public class BookController { @Autowired private BookService bookService;

@GetMapping("/{id}") public ResponseEntity getBookById(@PathVariable String id) { Book book = bookService.getBookById(id); return ResponseEntity.ok(book); }

@PostMapping public ResponseEntity createBook(@RequestBody Book book) { Book savedBook = bookService.createBook(book); return ResponseEntity.ok(savedBook); }

@PutMapping("/{id}") public ResponseEntity updateBook(@PathVariable String id, @RequestBody Book book) { Book savedBook = bookService.updateBook(id, book); return ResponseEntity.ok(savedBook); }

@DeleteMapping("/{id}") public ResponseEntity deleteBook(@PathVariable String id) { bookService.deleteBook(id); return ResponseEntity.noContent().build(); }}

Note: This class is identified as a Spring-managed controller component that manages HTTP requests by the @RestController annotation. GET, POST, PUT, and DELETE requests are mapped to the appropriate methods that use the BookService to carry out CRUD activities on the Elasticsearch cluster by the controller after injecting the @BookService dependency using the @Autowiredannotation.

I’m done now! Now that Elasticsearch is being used as the application’s data store and a REST API is available for interacting with the data, you have a Spring Boot application.

Step 4: CRUD operation Using curlCreate a new book:curl -X POST "http://localhost:8080/books" -H "Content-Type: application/json" -d '{"title":"New Book","author":"John Doe","description":"A new book"}'Retrieve a book by ID:curl -X GET "http://localhost:8080/books/{id}"

Note: replace {id} with the ID of the book, you want to retrieve.

Update a book:curl -X PUT "http://localhost:8080/books/{id}" -H "Content-Type: application/json" -d '{"title":"Updated Book","author":"Jane Smith","description":"An updated book"}'Delete a book:curl -X DELETE "http://localhost:8080/books/{id}"

These curl instructions will communicate with the Spring Boot application’s REST API to carry out the necessary CRUD actions on the Book entity. As previously noted, you may utilise the Elasticsearch API to confirm the modifications that these actions are making to the data.

If you enjoyed reading this, don’t forget the applause. 👏Thank you.

If you like what you read Buy me a cup of coffee.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有