Spring Boot整合elasticsearch的詳細(xì)步驟
一、簡(jiǎn)介
我們的應(yīng)用經(jīng)常需要添加檢索功能,開(kāi)源的 ElasticSearch 是目前全文搜索引擎的 首選。他可以快速的存儲(chǔ)、搜索和分析海量數(shù)據(jù)。Spring Boot通過(guò)整合Spring Data ElasticSearch為我們提供了非常便捷的檢索功能支持;
Elasticsearch是一個(gè)分布式搜索服務(wù),提供Restful API,底層基于Lucene,采用 多shard(分片)的方式保證數(shù)據(jù)安全,并且提供自動(dòng)resharding的功能,github 等大型的站點(diǎn)也是采用了ElasticSearch作為其搜索服務(wù),
我們建立一個(gè)網(wǎng)站或應(yīng)用程序,并要添加搜索功能,但是想要完成搜索工作的創(chuàng)建是非常困難的。我們希望搜索解決方案要運(yùn)行速度快,我們希望能有一個(gè)零配置和一個(gè)完全免費(fèi)的搜索模式,我們希望能夠簡(jiǎn)單地使用JSON通過(guò)HTTP來(lái)索引數(shù)據(jù),我們希望我們的搜索服務(wù)器始終可用,我們希望能夠從一臺(tái)開(kāi)始并擴(kuò)展到數(shù)百臺(tái),我們要實(shí)時(shí)搜索,我們要簡(jiǎn)單的多租戶,我們希望建立一個(gè)云的解決方案。因此我們利用Elasticsearch來(lái)解決所有這些問(wèn)題及可能出現(xiàn)的更多其它問(wèn)題。
二、安裝elasticsearch
我們采用 docker鏡像安裝的方式。
#下載鏡像 docker pull elasticsearch #啟動(dòng)鏡像,elasticsearch 啟動(dòng)是會(huì)默認(rèn)分配2G的內(nèi)存 ,我們啟動(dòng)是設(shè)置小一點(diǎn),防止我們內(nèi)存不夠啟動(dòng)失敗 #9200是elasticsearch 默認(rèn)的web通信接口,9300是分布式情況下,elasticsearch個(gè)節(jié)點(diǎn)通信的端口 docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name es01 5c1e1ecfe33a
訪問(wèn) 127.0.0.1:9200 如下圖,說(shuō)明安裝成功
三、elasticsearch的一些概念
以 員工文檔 的形式存儲(chǔ)為例:一個(gè)文檔代表一個(gè)員工數(shù)據(jù)。存儲(chǔ)數(shù)據(jù)到 ElasticSearch 的行為叫做索引 ,但在索引一個(gè)文檔之前,需要確定將文檔存 儲(chǔ)在哪里。
一個(gè) ElasticSearch 集群可以 包含多個(gè)索引 ,相應(yīng)的每個(gè)索引可以包含多個(gè)類(lèi)型。這些不同的類(lèi)型存儲(chǔ)著多個(gè)文檔 ,每個(gè)文檔又有 多個(gè) 屬性 。
類(lèi)似關(guān)系:
- 索引-數(shù)據(jù)庫(kù)
- 類(lèi)型-表
- 文檔-表中的記錄 – 屬性-列
elasticsearch使用可以參早官方文檔,在這里不在講解。
四、整合 elasticsearch
創(chuàng)建項(xiàng)目 springboot-elasticsearch,引入web支持
SpringBoot 提供了兩種方式操作elasticsearch,Jest 和 SpringData。
Jest 操作 elasticsearch
Jest是ElasticSearch的Java HTTP Rest客戶端。
ElasticSearch已經(jīng)有一個(gè)Java API,ElasticSearch也在內(nèi)部使用它,但是Jest填補(bǔ)了空白,它是ElasticSearch Http Rest接口缺少的客戶端。
1. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gf</groupId>
<artifactId>springboot-elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-elasticsearch</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
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測(cè)試類(lèi)
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)
@SpringBootTest
public class SpringbootElasticsearchApplicationTests {
@Autowired
JestClient jestClient;
@Test
public void createIndex() {
//1. 給ES中索引(保存)一個(gè)文檔
Article article = new Article();
article.setId( 1 );
article.setTitle( "好消息" );
article.setAuthor( "張三" );
article.setContent( "Hello World" );
//2. 構(gòu)建一個(gè)索引
Index index = new Index.Builder( article ).index( "gf" ).type( "news" ).build();
try {
//3. 執(zhí)行
jestClient.execute( index );
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void search() {
//查詢表達(dá)式
String query = "{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"content\" : \"hello\"\n" +
" }\n" +
" }\n" +
"}";
//構(gòu)建搜索功能
Search search = new Search.Builder( query ).addIndex( "gf" ).addType( "news" ).build();
try {
//執(zhí)行
SearchResult result = jestClient.execute( search );
System.out.println(result.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Jest的更多api ,可以參照github的文檔:https://github.com/searchbox-io/Jest
SpringData 操作 elasticsearch
1. application.properties
spring.data.elasticsearch.cluster-name=elasticsearch spring.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<Book, Integer>{
List<Book> findByBookNameLike(String bookName);
}
4. springboot 測(cè)試類(lèi)
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)
@SpringBootTest
public class SpringbootElasticsearchApplicationTests {
@Autowired
BookRepository bookRepository;
@Test
public void createIndex2(){
Book book = new Book();
book.setId(1);
book.setBookName("西游記");
book.setAuthor( "吳承恩" );
bookRepository.index( book );
}
@Test
public void useFind() {
List<Book> list = bookRepository.findByBookNameLike( "游" );
for (Book book : list) {
System.out.println(book);
}
}
}
我們啟動(dòng)測(cè)試 ,發(fā)現(xiàn)報(bào)錯(cuò) 。
這個(gè)報(bào)錯(cuò)的原因是springData的版本與我elasticsearch的版本有沖突,下午是springData官方文檔給出的適配表。
我們使用的springdata elasticsearch的 版本是3.1.3 ,對(duì)應(yīng)的版本應(yīng)該是6.2.2版本,而我們是的 elasticsearch 是 5.6.9,所以目前我們需要更換elasticsearch的版本為6.X
docker pull elasticsearch:6.5.1 docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name es02 鏡像ID
訪問(wèn)127.0.0.1:9200
集群名為docker-cluster,所以我們要修改application.properties的配置了
spring.data.elasticsearch.cluster-name=docker-cluster spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
我們?cè)俅芜M(jìn)行測(cè)試,測(cè)試可以通過(guò)了 。我們?cè)L問(wèn)http://127.0.0.1:9200/gf/book/1,可以得到我們存入的索引信息。
源碼:https://github.com/gf-huanchupk/SpringBootLearning
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java數(shù)據(jù)庫(kù)連接PreparedStatement的使用詳解
這篇文章主要介紹了Java數(shù)據(jù)庫(kù)連接PreparedStatement的使用詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
mybatis升級(jí)mybatis-plus時(shí)踩到的一些坑
這篇文章主要給大家介紹了關(guān)于mybatis升級(jí)mybatis-plus時(shí)踩到的一些坑,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
SpringBoot3.x循環(huán)依賴問(wèn)題解決方案
這篇文章主要介紹了SpringBoot3.x循環(huán)依賴的相關(guān)知識(shí),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
spring?boot?executable?jar/war?原理解析
spring boot里其實(shí)不僅可以直接以 java -jar demo.jar的方式啟動(dòng),還可以把jar/war變?yōu)橐粋€(gè)可以執(zhí)行的腳本來(lái)啟動(dòng),比如./demo.jar,這篇文章主要介紹了spring?boot?executable?jar/war?原理,需要的朋友可以參考下2023-02-02
springboot-jpa的實(shí)現(xiàn)操作
這篇文章主要介紹了springboot-jpa的實(shí)現(xiàn)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03

