In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, the editor will share with you the relevant knowledge about how to integrate elasticsearch in Spring Boot. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
I. brief introduction
Our applications often need to add retrieval functions, and open source ElasticSearch is the first choice of full-text search engines at present. He can quickly store, search and analyze huge amounts of data. Spring Boot provides us with very convenient retrieval function support by integrating Spring Data ElasticSearch.
Elasticsearch is a distributed search service, which provides Restful API, the underlying layer is based on Lucene, uses multi-shard (fragmentation) to ensure data security, and provides automatic resharding function. Large sites such as github also use ElasticSearch as their search service.
We build a website or application and want to add search functions, but it is very difficult to complete the search work. We want the search solution to run fast, we want to have a zero configuration and a completely free search mode, we want to be able to simply use JSON to index data through HTTP, we want our search server to be always available, we want to be able to start from one and expand to hundreds, we want real-time search, we want simple multi-tenancy, we want to build a cloud solution. So we use Elasticsearch to solve all these problems and many more that may arise.
Second, install elasticsearch
We use docker image installation method.
# download image docker pull elasticsearch# starts the image. 2GB of memory will be allocated by default when elasticsearch starts. When we start, we set it smaller to prevent us from running out of memory to start failure. # 9200 is the default web communication interface for elasticsearch, and 9300 is the port for elasticsearch nodes to communicate with each other in distributed case: docker run-e ES_JAVA_OPTS= "- Xms256m-Xmx256m"-d-p 9200 web 9200-p 9300 elasticsearch 9300-- name es01 5c1e1ecfe33a
Visit 127.0.0.1virtual 9200 as shown in the figure below, indicating that the installation is successful
III. Some concepts of elasticsearch
Take the storage in the form of an employee document as an example: a document represents an employee data. The act of storing data into ElasticSearch is called indexing, but before indexing a document, you need to determine where to store the document.
An ElasticSearch cluster can contain multiple indexes, and each index can contain multiple types. These different types store multiple documents, and each document has multiple properties.
Similar relationships:
Index-Database
Type-tabl
Document-records in the table-properties-columns
The use of elasticsearch can be seen in the official documentation, which is not explained here.
IV. Integrating elasticsearch
Create project springboot-elasticsearch and introduce web support
SpringBoot provides two ways to manipulate elasticsearch,Jest and SpringData.
Jest operation elasticsearch
Jest is the Java HTTP Rest client of ElasticSearch.
ElasticSearch already has a Java API,ElasticSearch that uses it internally, but Jest fills the gap, which is a missing client for the ElasticSearch Http Rest interface.
1. Pom.xml
4.0.0 com.gf springboot-elasticsearch 0.0.1-SNAPSHOT jar springboot-elasticsearch Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.1.1.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-data-elasticsearch io.searchbox jest 5.3.3 org.springframework.boot spring- Boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
2. Application.properties
Spring.elasticsearch.jest.uris= http://127.0.0.1:9200
3. Article
Package com.gf.entity;import io.searchbox.annotations.JestId;public class Article {@ JestId private Integer id; private String author; private String title; private String content; public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getAuthor () {return author;} public void setAuthor (String author) {this.author = author;} public String getTitle () {return title } public void setTitle (String title) {this.title = title;} public String getContent () {return content;} public void setContent (String content) {this.content = content;} @ Override public String toString () {final StringBuilder sb = new StringBuilder ("{\" Article\ ": {"); sb.append ("\" id\ ":") .append (id) Sb.append (",\" author\ ":\") .append (author). Append ('\ "); sb.append (",\ "title\":\ ") .append (title). Append ('\"); sb.append (",\" content\ ":\") .append (content). Append ('\ ") Sb.append ("}}"); return sb.toString ();}}
4. Springboot test class
Package com.gf;import com.gf.entity.Article;import io.searchbox.client.JestClient;import io.searchbox.core.Index;import io.searchbox.core.Search;import io.searchbox.core.SearchResult;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.io.IOException;@RunWith (SpringRunner.class) @ SpringBootTestpublic class SpringbootElasticsearchApplicationTests {@ Autowired JestClient jestClient Test public void createIndex () {/ / 1. Index (save) a document in ES Article article = new Article (); article.setId (1); article.setTitle ("good news"); article.setAuthor ("Zhang San"); article.setContent ("Hello World"); / / 2. Build an index Index index = new Index.Builder (article). Index ("gf"). Type ("news"). Build (); try {/ / 3. Execute jestClient.execute (index);} catch (IOException e) {e.printStackTrace () } @ Test public void search () {/ / query expression String query = "{\ n" + "\" query\ ": {\ n" + "\" match\ ": {\ n" + "\" content\ ":\" hello\ "\ n" + "}\ n" + "}\ n" + "} / / build search function Search search = new Search.Builder (query). AddIndex ("gf"). AddType ("news"). Build (); try {/ / execute SearchResult result = jestClient.execute (search); System.out.println (result.getJsonString ());} catch (IOException e) {e.printStackTrace ();}
For more api of Jest, you can refer to github's documentation: https://github.com/searchbox-io/Jest
SpringData operation elasticsearch
1. Application.properties
Spring.data.elasticsearch.cluster-name=elasticsearchspring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
2. Book
Package com.gf.entity;@Document (indexName = "gf", type = "book") public class Book {private Integer id; private String bookName; private String author; public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getBookName () {return bookName;} public void setBookName (String bookName) {this.bookName = bookName;} public String getAuthor () {return author } public void setAuthor (String author) {this.author = author;} @ Override public String toString () {final StringBuilder sb = new StringBuilder ("{\" Book\ ": {"); sb.append ("\" id\ ":") .append (id); sb.append (",\" bookName\ ":\") .append (bookName). Append ('\ "') Sb.append (",\" author\ ":\") .append (author). Append ('\ "); sb.append ("}} "); return sb.toString ();}}
3. BookRepository
Package com.gf.repository;import com.gf.entity.Book;import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;import java.util.List;public interface BookRepository extends ElasticsearchRepository {List findByBookNameLike (String bookName);}
4. Springboot test class
Package com.gf;import com.gf.entity.Article;import com.gf.entity.Book;import com.gf.repository.BookRepository;import io.searchbox.client.JestClient;import io.searchbox.core.Index;import io.searchbox.core.Search;import io.searchbox.core.SearchResult;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.io.IOException Import java.util.List;@RunWith (SpringRunner.class) @ SpringBootTestpublic class SpringbootElasticsearchApplicationTests {@ Autowired BookRepository bookRepository; @ Testpublic void createIndex2 () {Book book = new Book (); book.setId (1); book.setBookName (Journey to the West); book.setAuthor (Wu Chengen); bookRepository.index (book);} @ Testpublic void useFind () {List list = bookRepository.findByBookNameLike ("Tour") For (Book book: list) {System.out.println (book);}
We started the test and found an error.
The reason for this error is that there is a conflict between the version of springData and my version of elasticsearch. The afternoon is the adaptation table given by the official springData documentation.
The version of springdata elasticsearch we use is 3.1.3, and the corresponding version should be 6.2.2, while our elasticsearch is 5.6.9, so we need to change the version of elasticsearch to 6.x.
Docker pull elasticsearch:6.5.1docker run-e ES_JAVA_OPTS= "- Xms256m-Xmx256m"-d-p 9200 Xmx256m 9200-p 9300 Xms256m 9300-name es02 mirror ID
Visit 127.0.0.1VR 9200
The cluster is named docker-cluster, so we need to modify the configuration of application.properties.
Spring.data.elasticsearch.cluster-name=docker-clusterspring.data.elasticsearch.cluster-nodes=127.0.0.1:9300 above is all the content of the article "how to integrate elasticsearch in Spring Boot". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.