ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。
我们建立一个网站或应用程序,并要添加搜索功能,但是想要完成搜索工作的创建是非常困难的。我们希望搜索解决方案要运行速度快,我们希望能有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用JSON通过HTTP来索引数据,我们希望我们的搜索服务器始终可用,我们希望能够从一台开始并扩展到数百台,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。因此我们利用Elasticsearch来解决所有这些问题及可能出现的更多其它问题。
下载elasticsearch-2.4.2.rar, 解压后运行其中 bin 目录的 elasticsearch.bat,可以看到如图所示的界面。
elasticsearch 提供了一个可视化的客户端 kibana,下载后解压后运行 bin 目录下的 kibana.bat 。
1.项目中增加pom
文件中加入elasticsearch
依赖
org.springframework.boot
spring-boot-starter-data-elasticsearch
2.为配置文件在最后加上 es
相关配置
spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300
3.新建一个商品实体类Product
其中需要注意:
indexName:索引名称 可以理解为数据库名 必须为小写 不然会报org.elasticsearch.indices.InvalidIndexNameException异常
type:类型 可以理解为表名
package com.zgw.tmall.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* Created by Zhaogw&Lss on 2018/11/6.
*/
@Entity
@Table(name = "product")
@JsonIgnoreProperties({"handler","hibernateLazyInitializer"})
@Document(indexName = "tmall_springboot",type = "product")
public class Product implements Serializable{
private static final long serialVersionUID = 6967408083333555121L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
int id;
@ManyToOne
@JoinColumn(name = "cid")
private Category category;
//如果既没有指明 关联到哪个Column,又没有明确要用@Transient忽略,那么就会自动关联到表对应的同名字段
private String name;
private String subTitle;
private float originalPrice;
private float promotePrice;
private int stock;
private Date createDate;
@Transient
private ProductImage firstProductImage;
public List getProductSingleImages() {
return productSingleImages;
}
public void setProductSingleImages(List productSingleImages) {
this.productSingleImages = productSingleImages;
}
public List getProductDetailImages() {
return productDetailImages;
}
public void setProductDetailImages(List productDetailImages) {
this.productDetailImages = productDetailImages;
}
public int getReviewCount() {
return reviewCount;
}
public void setReviewCount(int reviewCount) {
this.reviewCount = reviewCount;
}
public int getSaleCount() {
return saleCount;
}
public void setSaleCount(int saleCount) {
this.saleCount = saleCount;
}
@Transient
private List productSingleImages;
@Transient
private List productDetailImages;
@Transient
private int reviewCount;
@Transient
private int saleCount;
public ProductImage getFirstProductImage() {
return firstProductImage;
}
public void setFirstProductImage(ProductImage firstProductImage) {
this.firstProductImage = firstProductImage;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public float getOriginalPrice() {
return originalPrice;
}
public void setOriginalPrice(float originalPrice) {
this.originalPrice = originalPrice;
}
public float getPromotePrice() {
return promotePrice;
}
public void setPromotePrice(float promotePrice) {
this.promotePrice = promotePrice;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", category=" + category +
", name='" + name + '\'' +
", subTitle='" + subTitle + '\'' +
", originalPrice=" + originalPrice +
", promotePrice=" + promotePrice +
", stock=" + stock +
", createDate=" + createDate +
'}';
}
}
创建ProductESDAO
,继承ElasticsearchRepository
,代码如下
package com.zgw.tmall.es;
import com.zgw.tmall.pojo.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Created by Zhaogw&Lss on 2019/6/20.
*/
public interface ProductESDAO extends ElasticsearchRepository {
}
ProductService
增加,删除,修改的时候,除了通过 ProductDAO
对数据库产生影响之外,还要通过 ProductESDAO
同步到 es
.
package com.zgw.tmall.service;
import com.zgw.tmall.dao.ProductDAO;
import com.zgw.tmall.es.ProductESDAO;
import com.zgw.tmall.pojo.Category;
import com.zgw.tmall.pojo.Product;
import com.zgw.tmall.util.Page4Navigator;
import com.zgw.tmall.util.SpringContextUtil;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Zhaogw&Lss on 2018/11/7.
*/
@Service
@CacheConfig(cacheNames="products")
public class ProductService {
@Autowired ProductDAO productDAO;
@Autowired ProductImageService productImageService;
@Autowired CategoryService categoryService;
@Autowired OrderItemService orderItemService;
@Autowired ReviewService reviewService;
@Autowired
ProductESDAO productESDAO;
@CacheEvict(allEntries=true)
public void add(Product bean) {
productDAO.save(bean);
productESDAO.save(bean);
}
@CacheEvict(allEntries=true)
public void delete(int id) {
productDAO.delete(id);
productESDAO.delete(id);
}
@Cacheable(key="'products-one-'+ #p0")
public Product get(int id) {
return productDAO.findOne(id);
}
@CacheEvict(allEntries=true)
public void update(Product bean) {
productDAO.save(bean);
productESDAO.save(bean);
}
@Cacheable(key="'products-cid-'+#p0+'-page-'+#p1 + '-' + #p2 ")
public Page4Navigator list(int cid, int start, int size,int navigatePages) {
Category category = categoryService.get(cid);
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(start, size, sort);
Page pageFromJPA =productDAO.findByCategory(category,pageable);
return new Page4Navigator<>(pageFromJPA,navigatePages);
}
public void fill(List categorys) {
for (Category category : categorys) {
fill(category);
}
}
@Cacheable(key="'products-cid-'+ #p0.id")
public List listByCategory(Category category){
return productDAO.findByCategoryOrderById(category);
}
public void fill(Category category) {
ProductService productService = SpringContextUtil.getBean(ProductService.class);
List products = productService.listByCategory(category);
productImageService.setFirstProdutImages(products);
category.setProducts(products);
}
public void fillByRow(List categorys) {
int productNumberEachRow = 8;
for (Category category : categorys) {
List products = category.getProducts();
List> productsByRow = new ArrayList<>();
for (int i = 0; i < products.size(); i+=productNumberEachRow) {
int size = i+productNumberEachRow;
size= size>products.size()?products.size():size;
List productsOfEachRow =products.subList(i, size);
productsByRow.add(productsOfEachRow);
}
category.setProductsByRow(productsByRow);
}
}
public void setSaleAndReviewNumber(Product product) {
int saleCount = orderItemService.getSaleCount(product);
product.setSaleCount(saleCount);
int reviewCount = reviewService.getCount(product);
product.setReviewCount(reviewCount);
}
public void setSaleAndReviewNumber(List products) {
for (Product product : products)
setSaleAndReviewNumber(product);
}
//查询的修改。 以前查询是模糊查询,现在通过 ProductESDAO 到 elasticsearch 中进行查询了。
public List search(String keyword, int start, int size) {
initDatabase2ES();
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
.add(QueryBuilders.matchPhraseQuery("name", keyword),
ScoreFunctionBuilders.weightFactorFunction(100))
.scoreMode("sum")
.setMinScore(10);
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(start, size, sort);
//es搜索默认第一页页码是0
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withPageable(pageable)
.withQuery(functionScoreQueryBuilder).build();
Page page = productESDAO.search(searchQuery);
return page.getContent();
}
/** 初始化数据到es. 因为数据刚开始都在数据库中,不在es中,所以刚开始查询,
先看看es有没有数据,如果没有,就把数据从数据库同步到es中*/
private void initDatabase2ES() {
Pageable pageable = new PageRequest(0, 5);
Page page =productESDAO.findAll(pageable);
if(page.getContent().isEmpty()) {
List products= productDAO.findAll();
for (Product product : products) {
productESDAO.save(product);
}
}
}
}
启动项目测试:搜索关键字‘车’显示如下内容,一共显示十一条信息。
根据控制台日志会发现第一次查询会执行 sql语句,而进行第二次搜索‘车’,以后再查询,就不会执行 sql 语句了。
也可以通过客户端访问:http://127.0.0.1:5601
通过搜索车关键字:一共显示十一条信息
ok,SpringBoot整合Spring Data Elasticsearch到此完结
要是还有不太明白的地方请留言,评论必回
要是对我的文章感兴趣的话,关注一下吧,谢谢!