Elasticsearch
Elasticsearch (ES)是一個基于Lucene構建的開源、分布式、RESTful 介面全文搜索引擎,Elasticsearch 還是一個分布式檔案資料庫,其中每個欄位均是被索引的資料且可被搜索,它能夠擴展至數以百計的服務器存盤以及處理PB級的資料,它可以在很短的時間內在存盤、搜索和分析大量的資料,它通常作為具有復雜搜索場景情況下的核心發動機,es是由java語言撰寫的,
Elasticsearch就是為高可用和可擴展而生的,可以通過購置性能更強的服務器來完成,
官網
Elasticsearch:官方分布式搜索和分析引擎 | Elastic
https://www.elastic.co/cn/elasticsearch/
Spring Data
Spring Data是Spring 的一個子專案,用于簡化資料庫訪問,支持NoSQL和關系資料庫存盤,其主要目標是使資料庫的訪問變得方便快捷,
官網
Spring DataLevel up your Java code and explore what Spring can do for you.https://spring.io/projects/spring-data
Spring Data ElasticSearch
Spring Data ElasticSearch 基于 spring data API 簡化 elasticSearch操作,將原始操作elasticSearch的客戶端API進行封裝,Spring Data為Elasticsearch專案提供集成搜索引擎,Spring Data Elasticsearch POJO的關鍵功能區域為中心的模型與Elastichsearch互動檔案和輕松地撰寫一個存盤庫資料訪問層,
官網
Spring Data Elasticsearch
https://spring.io/projects/spring-data-elasticsearch
代碼
創建maven專案,并引入依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.6.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
</dependencies>
在resources檔案夾下創建application.properties檔案

application.properties內容如下
# es 服務地址
elasticsearch.host=部署es服務器的ip
# es 服務埠
elasticsearch.port=9200
# 配置日志級別,開啟 debug 日志
logging.level.com.es=debug
創建MainApplication
package com.es;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
創建ElasticSearch組態檔ElasticsearchConfig
package com.es.config;
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
private String host ;
private Integer port ;
@Override
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
RestHighLevelClient restHighLevelClient = new
RestHighLevelClient(builder);
return restHighLevelClient;
}
}
創建物體類Person
package com.es.DO;
import lombok.Data;
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;
@Data
@Document(indexName = "contact", shards = 3, replicas = 1)
public class Person {
/**
* 主鍵 id
*/
@Id
public Long id;
/**
* 姓名 name
*/
@Field(type = FieldType.Text, analyzer = "ik_max_word")
public String name;
/**
* 年齡 age
*/
@Field(type = FieldType.Integer)
public int age;
/**
* 地址 address
*/
@Field(type = FieldType.Keyword, index = false)
public String address;
}
配置Person的Dao類,PersonDao
package com.es.dao;
import com.es.DO.Person;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonDao extends ElasticsearchRepository<Person, Long>{
}
創建測驗類SpringDataESIndexTest,測驗類跟啟動類在同一個包下,不然啟動會報錯,
package com.es.test;
import com.es.DO.Person;
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.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESIndexTest {
//注入 ElasticsearchRestTemplate
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
//創建索引并增加映射配置
@Test
public void createIndex(){
//創建索引,系統初始化會自動創建索引
System.out.println("創建索引");
}
@Test
public void deleteIndex(){
//創建索引,系統初始化會自動創建索引
boolean flg = elasticsearchRestTemplate.deleteIndex(Person.class);
System.out.println("洗掉索引 = " + flg);
}
}
測驗
對索引創建及洗掉進行測驗
http://IP地址:9200/_cat/indices?v,用瀏覽器或Postman等工具訪問該地址來看結果
運行createIndex測驗方法


運行deleteIndex測驗方法


檔案操作
新加SpringDataESPersonDaoTest測驗類
新增
@Autowired
private PersonDao personDao;
/**
* 新增
*/
@Test
public void save(){
Person person = new Person();
person.setId(1L);
person.setName("張三");
person.setAge(21);
person.setAddress("北京市海淀區");
personDao.save(person);
}

測驗地址:http://IP地址:9200/contact/_doc/1

修改
@Autowired
private PersonDao personDao;
//修改
@Test
public void update(){
Person person = new Person();
person.setId(1L);
person.setName("張三");
person.setAge(21);
person.setAddress("北京市朝陽區");
personDao.save(person);
}

測驗地址:http://IP地址:9200/contact/_doc/1

根據 id 查詢
@Autowired
private PersonDao personDao;
//根據 id 查詢
@Test
public void findById(){
Person person = personDao.findById(1L).get();
System.out.println(person);
}
列印成功

列印所有
@Autowired
private PersonDao personDao;
@Test
public void findAll(){
Iterable<Person> persons = personDao.findAll();
for (Person person : persons) {
System.out.println(person);
}
}

洗掉
@Autowired
private PersonDao personDao;
@Test
public void delete(){
Person person = new Person();
person.setId(1L);
personDao.delete(person);
}

測驗地址:http://IP地址:9200/contact/_doc/1
已洗掉
批量新增
@Autowired
private PersonDao personDao;
//批量新增
@Test
public void saveAll(){
List<Person> personList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Person person = new Person();
person.setId(Long.valueOf(i));
person.setName("["+i+"]張三");
person.setAge(21+i);
person.setAddress("北京市海淀區");
personList.add(person);
}
personDao.saveAll(personList);
}

測驗地址:http://ip地址:9200/contact/_search

分頁查詢
@Autowired
private PersonDao personDao;
@Test
public void findByPageable(){
//設定排序(排序方式,正序還是倒序,排序的 id)
Sort sort = Sort.by(Sort.Direction.DESC,"id");
int currentPage=0;//當前頁,第一頁從 0 開始, 1 表示第二頁
int pageSize = 5;//每頁顯示多少條
//設定查詢分頁
PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
//分頁查詢
Page<Person> personPage = personDao.findAll(pageRequest);
for (Person person : personPage.getContent()) {
System.out.println(person);
}
}
查詢成功,查出第一頁

完整代碼如下
package com.es.test;
import com.es.DO.Person;
import com.es.dao.PersonDao;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESPersonDaoTest {
@Autowired
private PersonDao personDao;
/**
* 新增
*/
@Test
public void save(){
Person person = new Person();
person.setId(1L);
person.setName("張三");
person.setAge(21);
person.setAddress("北京市海淀區");
personDao.save(person);
}
//POSTMAN, GET http://IP地址:9200/contact/_doc/1
//修改
@Test
public void update(){
Person person = new Person();
person.setId(1L);
person.setName("張三");
person.setAge(21);
person.setAddress("北京市朝陽區");
personDao.save(person);
}
//POSTMAN, GET http://IP地址:9200/contact/_doc/1
//根據 id 查詢
@Test
public void findById(){
Person person = personDao.findById(1L).get();
System.out.println(person);
}
@Test
public void findAll(){
Iterable<Person> persons = personDao.findAll();
for (Person person : persons) {
System.out.println(person);
}
}
//洗掉
@Test
public void delete(){
Person person = new Person();
person.setId(1L);
personDao.delete(person);
}
//POSTMAN, GET http://IP地址:9200/contact/_doc/1
//批量新增
@Test
public void saveAll(){
List<Person> personList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Person person = new Person();
person.setId(Long.valueOf(i));
person.setName("["+i+"]張三");
person.setAge(21+i);
person.setAddress("北京市海淀區");
personList.add(person);
}
personDao.saveAll(personList);
}
//分頁查詢
@Test
public void findByPageable(){
//設定排序(排序方式,正序還是倒序,排序的 id)
Sort sort = Sort.by(Sort.Direction.DESC,"id");
int currentPage=0;//當前頁,第一頁從 0 開始, 1 表示第二頁
int pageSize = 5;//每頁顯示多少條
//設定查詢分頁
PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
//分頁查詢
Page<Person> personPage = personDao.findAll(pageRequest);
for (Person person : personPage.getContent()) {
System.out.println(person);
}
}
}
檔案搜索
新建測驗類SpringDataESSearchTest
termQuery
@Autowired
private PersonDao personDao;
/**
* term 查詢
* search(termQueryBuilder) 呼叫搜索方法,引數查詢構建器物件
*/
@Test
public void termQuery(){
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]張三");
Iterable<Person> persons = personDao.search(termQueryBuilder);
for (Person person : persons) {
System.out.println(person);
}
}

termQuery加分頁
@Autowired
private PersonDao personDao;
/**
* term 查詢加分頁
*/
@Test
public void termQueryByPage(){
int currentPage= 0 ;
int pageSize = 5;
//設定查詢分頁
PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]張三");
Iterable<Person> persons =
personDao.search(termQueryBuilder,pageRequest);
for (Person person : persons) {
System.out.println(person);
}
}
只有一條name為[8]張三的記錄

完整代碼如下
package com.es.test;
import com.es.DO.Person;
import com.es.dao.PersonDao;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
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.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESSearchTest {
@Autowired
private PersonDao personDao;
/**
* term 查詢
* search(termQueryBuilder) 呼叫搜索方法,引數查詢構建器物件
*/
@Test
public void termQuery(){
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]張三");
Iterable<Person> persons = personDao.search(termQueryBuilder);
for (Person person : persons) {
System.out.println(person);
}
}
/**
* term 查詢加分頁
*/
@Test
public void termQueryByPage(){
int currentPage= 0 ;
int pageSize = 5;
//設定查詢分頁
PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]張三");
Iterable<Person> persons =
personDao.search(termQueryBuilder,pageRequest);
for (Person person : persons) {
System.out.println(person);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/423334.html
標籤:其他
上一篇:Maven是什么
