咱們今天就來爲你們講解spring-data-elasticsearch這種方式來集成es。爲什們推薦這種呢,由於這種方式spring爲咱們封裝了常見的es操做。和使用jpa操做數據庫同樣方便。用過jpa的同窗必定知道。html
public interface UserRepository extends JpaRepository<UserBean, Long> {}
複製代碼
public interface UserESRepository extends ElasticsearchRepository<UserBean, Long> {}
複製代碼
springboot版本 | Elasticsearch版本 |
---|---|
2.1.3.RELEASE | 6.4.3 |
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qcl</groupId>
<artifactId>es</artifactId>
<version>0.0.1</version>
<name>es</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</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>
複製代碼
spring-boot-starter-data-elasticsearch:就是咱們所須要集成的es。java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
複製代碼
這裏下載本地elasticsearch,其實和咱們下載本地mysql是同樣的,你要用elasticsearch確定要下載一個本地版本用來存儲查詢數據啊。 下面來簡單的講解下elasticsearch版本的下載步驟node
1,到官網 www.elastic.co/downloads/ mysql
2,下載成功後解壓,並進入到config文件夾下 web
# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
# Before you set out to tweak and tune the configuration, make sure you
# understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: 0.0.0.0
#
# Set a custom port for HTTP:
#
http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes:
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true
#qcl本身加的
http.cors.enabled: true
http.cors.allow-origin: "*"
node.master: true
node.data: true
複製代碼
這裏的cluster.name: my-application就表明咱們的es的名稱叫my-applicationspring
在建立的springboot項目下的application.yml作以下配置 sql
#url相關配置,這裏配置url的基本url
server:
port: 8080
spring:
## Elasticsearch配置文件(必須)
## 該配置和Elasticsearch本地文件config下的elasticsearch.yml中的配置信息有關
data:
elasticsearch:
cluster-name: my-application
cluster-nodes: 127.0.0.1:9300
複製代碼
package com.qcl.es;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* Created by qcl on 2018/7/10.
* ES相關
*/
@Document(indexName = "user", type = "docs", shards = 1, replicas = 0)
public class UserES {
//主鍵自增加
@Id
private Long id;//主鍵
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String userName;
private String userPhone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
@Override
public String toString() {
return "UserES{" +
"userId=" + id +
", userName='" + userName + '\'' + ", userPhone='" + userPhone + '\'' + '}'; } } 複製代碼
package com.qcl.es;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Created by qcl on 2019-03-23
* 微信:2501902696
* desc:
*/
public interface UserESRepository extends ElasticsearchRepository<UserES, Long> {}
複製代碼
package com.qcl.es;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by qcl on 2019-03-23
* 微信:2501902696
* desc:
*/
@RestController
public class UserController {
@Autowired
private UserESRepository repositoryES;
@GetMapping("/create")
public String create(
@RequestParam("id") Long id,
@RequestParam("userName") String userName,
@RequestParam("userPhone") String userPhone) {
UserES userES = new UserES();
userES.setId(id);
userES.setUserName(userName);
userES.setUserPhone(userPhone);
return repositoryES.save(userES).toString();
}
private String names;
@GetMapping("/get")
public String get() {
names = "";
Iterable<UserES> userES = repositoryES.findAll();
userES.forEach(userES1 -> {
names += userES1.toString() + "\n";
});
return names;
}
private String searchs = "";
@GetMapping("/search")
public String search(@RequestParam("searchKey") String searchKey) {
searchs = "";
// 構建查詢條件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本分詞查詢
queryBuilder.withQuery(QueryBuilders.matchQuery("userName", searchKey));
// 搜索,獲取結果
Page<UserES> items = repositoryES.search(queryBuilder.build());
// 總條數
long total = items.getTotalElements();
searchs += "總共數據數:" + total + "\n";
items.forEach(userES -> {
searchs += userES.toString() + "\n";
});
return searchs;
}
}
複製代碼
啓動springboot項目 數據庫
咱們簡單的實現了apache
插入一個userName='李四'&userPhone='272501902696'的數據 http://localhost:8080/create?id=5&userName='李四'&userPhone='272501902696' bootstrap
查詢上面的數據是否插入成功,能夠看到李四這條數據已經成功插入。
搜索 userName包含'四'的信息,能夠看到,成功感搜索到一條
搜索 userName包含'石'的信息,能夠看到,成功感搜索到4條
若是你有springboot相關的問題能夠加我微信交流 2501902696(備註java)