Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口
本教程是本人親自實戰(zhàn)的,然后運(yùn)行起來的全部步驟。
準(zhǔn)備工作
環(huán)境
Elasticsearch 7.15.2
Kibana 7.15.2
springboot 2.6.4 以及對應(yīng)的spring-boot-starter-web和spring-boot-starter-data-elasticsearch
fastjson 1.2.97
- 安裝好Elasticsearch7.15.2以及對應(yīng)的Kibana。
- 去Springboot Start 新建項目
在Kibana中新建索引book
使用 devtools 創(chuàng)建
# 新增索引
PUT book
{
"settings" : {
"number_of_shards" : 5,
"number_of_replicas" : 0,
"refresh_interval": "5s",
"index.mapping.ignore_malformed": true
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"author": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"postDate": {
"type": "keyword"
}
}
}
}
number_of_shards 數(shù)據(jù)分片 默認(rèn)為5
number_of_replicas 數(shù)據(jù)備份數(shù),如果只有一臺機(jī)器,建議設(shè)置為0,避免索引一直處于yellow狀態(tài)
查看是否創(chuàng)建成功
HEAD book
返回如下,即為創(chuàng)建索引成功
200 - OK
搜素 book 里面的信息
POST book/_search
{
"from": 0,
"size": 20
}
新建springboot項目
Springboot Start 新建項目
點(diǎn)擊generate就會獲取一個zip的包。這個就是生成的項目哦。
打開項目
項目完成之后的完整目錄:
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 https://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.6.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wumeng</groupId>
<artifactId>esapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>esapi</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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>ali-maven</id>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
</repositories>
</project>
application.properties 文件
# ELASTICSEARCH (ElasticsearchProperties)
# Whether to enable Elasticsearch repositories.
spring.data.elasticsearch.repositories.enabled=true
spring.elasticsearch.uris=http://192.168.0.119:9200
spring.elasticsearch.username=elastic
spring.elasticsearch.password=12345678
spring.elasticsearch.socket-timeout=30
修改成自己的用戶名和密碼哦
BookBean.java 文件
import lombok.Builder;
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
@Builder
@Document(indexName = "book")
public class BookBean {
private @Id String id;
@Field(analyzer = "ik_max_word",type = FieldType.Text)
private String title;
@Field(analyzer = "ik_max_word",type = FieldType.Text)
private String author;
private String postDate;
public BookBean(){}
public BookBean(String id, String title, String author, String postDate) {
this.id = id;
this.title = title;
this.author = author;
this.postDate = postDate;
}
}
BookRepository.java 文件
import com.wumeng.esapi.model.BookBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface BookRepository extends ElasticsearchRepository<BookBean,String> {
//Optional<BookBean> findById(String id);
Page<BookBean> findByAuthor(String author, Pageable pageable);
Page<BookBean> findByTitle(String title, Pageable pageable);
@Query("{\"match\": {\"title\": {\"query\": \"?0\"}}}")
Page<BookBean> findByTitle_custom(String keyword, Pageable pageable);
}
BookService.java 文件
import com.wumeng.esapi.model.BookBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import java.util.List;
import java.util.Optional;
public interface BookService {
Optional<BookBean> findById(String id);
BookBean save(BookBean blog);
void delete(BookBean blog);
Optional<BookBean> findOne(String id);
List<BookBean> findAll();
Page<BookBean> findByAuthor(String author, PageRequest pageRequest);
Page<BookBean> findByTitle(String title, PageRequest pageRequest);
List<BookBean> searchByKeyword(String keyword, PageRequest pageRequest);
}
BookServiceImpl.java 文件
import com.wumeng.esapi.repository.BookRepository;
import com.wumeng.esapi.model.BookBean;
import com.wumeng.esapi.service.BookService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class BookServiceImpl implements BookService {
@Autowired
@Qualifier("bookRepository")
private BookRepository bookRepository;
@Autowired
private ElasticsearchOperations elasticsearchOperations;
@Override
public Optional<BookBean> findById(String id) {
//CrudRepository中的方法
return bookRepository.findById(id);
}
@Override
public BookBean save(BookBean blog) {
return bookRepository.save(blog);
}
@Override
public void delete(BookBean blog) {
bookRepository.delete(blog);
}
@Override
public Optional<BookBean> findOne(String id) {
return bookRepository.findById(id);
}
@Override
public List<BookBean> findAll() {
return (List<BookBean>) bookRepository.findAll();
}
@Override
public Page<BookBean> findByAuthor(String author, PageRequest pageRequest) {
return bookRepository.findByAuthor(author,pageRequest);
}
@Override
public Page<BookBean> findByTitle(String title, PageRequest pageRequest) {
return bookRepository.findByTitle(title,pageRequest);
}
// @Override
// public Page<BookBean> searchByKeyword(String keyword, PageRequest pageRequest) {
// return bookRepository.searchByKeyword(keyword, pageRequest);
// }
@Override
public List<BookBean> searchByKeyword(String keyword, PageRequest pageRequest) {
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
// 查詢必須滿足的條件
// boolQueryBuilder.must(QueryBuilders.termQuery("studentSex", "女"));
// 查詢可能滿足的條件
// boolQueryBuilder.should(QueryBuilders.termQuery("gradeNumber", "一年級"));
// boolQueryBuilder.should(QueryBuilders.termQuery("gradeNumber", "二年級"));
// boolQueryBuilder.should(QueryBuilders.termQuery("gradeNumber", "三年級"));//精確
boolQueryBuilder.should(QueryBuilders.matchQuery("title",keyword));//模糊
boolQueryBuilder.should(QueryBuilders.matchQuery("author",keyword));
// 設(shè)置在可能滿足的條件中,至少必須滿足其中1條
// boolQueryBuilder.minimumShouldMatch(1);
// 必須不滿足的條件
// boolQueryBuilder.mustNot(QueryBuilders.termQuery("age", 8));
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//查詢
nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
//排序
nativeSearchQueryBuilder.withSorts(SortBuilders.fieldSort("postDate").order(SortOrder.ASC));
//分頁
nativeSearchQueryBuilder.withPageable(pageRequest);
//搜索
NativeSearchQuery nativeSearchQuery = nativeSearchQueryBuilder.build();
SearchHits<BookBean> productHits = this.elasticsearchOperations.search(nativeSearchQuery, BookBean.class, IndexCoordinates.of("book"));
List<BookBean> productMatches = new ArrayList<BookBean>();
productHits.forEach(searchHit->{
productMatches.add(searchHit.getContent());
});
return productMatches;
}
}
BookController.java 文件
import com.alibaba.fastjson.JSON;
import com.wumeng.esapi.service.BookService;
import com.wumeng.esapi.model.BookBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("book")
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/id/{id}")
@ResponseBody
public BookBean getBookById(@PathVariable String id){
Optional<BookBean> opt =bookService.findById(id);
BookBean book=opt.get();
System.out.println(book);
return book;
}
@RequestMapping("/save")
@ResponseBody
public String Save(){
BookBean book=new BookBean("1","ES入門教程","你剛回來了","2022-03-09");
System.out.println(book);
bookService.save(book);
book=new BookBean("2","ES入門教程","你剛回來了","2022-03-09");
System.out.println(book);
bookService.save(book);
book=new BookBean("3","ES入門教程","你剛回來了","2022-03-09");
System.out.println(book);
bookService.save(book);
return "Save success.";
}
@RequestMapping("/search/{keyword}")
@ResponseBody
public String searchBookByKeyWord(@PathVariable String keyword){
List<BookBean> list = bookService.searchByKeyword(keyword,PageRequest.of(0,200));
System.out.println(list);
return JSON.toJSONString(list);
}
}
運(yùn)行項目,跑起來。
插入信息
訪問地址:http://127.0.0.1:8080/book/save
Save success.
根據(jù)id查詢信息
訪問地址:http://127.0.0.1:8080/book/id/1
{"id":"1","title":"ES入門教程","author":"你剛回來了","postDate":"2022-03-09"}
模糊查詢titie 和author
訪問地址:http://127.0.0.1:8080/book/search/ES文章來源:http://www.zghlxwxcb.cn/news/detail-403105.html
[{"author":"你剛回來了","id":"2","postDate":"2022-03-09","title":"ES入門教程"},{"author":"你剛回來了","id":"1","postDate":"2022-03-09","title":"ES入門教程"}]
此次,項目簡單基本雛形已經(jīng)有了,可以繼續(xù)開發(fā)其他任務(wù)了。文章來源地址http://www.zghlxwxcb.cn/news/detail-403105.html
到了這里,關(guān)于Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!