Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate elasticsearch with Spring Boot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces you how to integrate Spring Boot elasticsearch, the content is very detailed, interested friends can refer to, hope to be helpful to you.

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.

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:92003. Articlepackage 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; @ Testpublic 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 operates elasticsearch1. Application.propertiesspring.data.elasticsearch.cluster-name=elasticsearchspring.data.elasticsearch.cluster-nodes=127.0.0.1:93002. Bookpackage 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. BookRepositorypackage 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);} @ Test public void useFind () {List list = bookRepository.findByBookNameLike ("you"); 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 on how to integrate Spring Boot elasticsearch to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report