ES在搜索和数据分析中的应用越来越广泛,在之前项目中对ES的使用有些心得,最近有不少朋友和同事都问到了ES,刚好最近也有些时间,所以打算通过8~10篇文章介绍下ES.(其实我也不知道最终会写下多少篇),为了保持阅读的连贯性,可以先看前面几篇文章:
ES搜索引擎入门+最佳实践(一)_flame.liu的博客-CSDN博客
ES搜索引擎入门+最佳实践(二)_flame.liu的博客-CSDN博客
ES搜索引擎入门+最佳实践(三)_flame.liu的博客-CSDN博客
ES搜索引擎入门+最佳实践(四)_flame.liu的博客-CSDN博客
ES搜索引擎入门+最佳实践(五)_flame.liu的博客-CSDN博客
ES搜索引擎入门+最佳实践(六)_flame.liu的博客-CSDN博客
ES搜索引擎入门+最佳实践(七):聚合_flame.liu的博客-CSDN博客
一.概要
创建一个电商平台对商品搜索的一个案例.可以实现对商品标题的搜索排序,数据的聚合,排序方式可以考虑有多种:商品相关性,距离,好评率,价格等.
二.准备数据
2.1 准备数据库
使用mysql数据库,表结构设计如下:
CREATE TABLE `product_detail` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
`uid` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'UID',
`productName` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品名称',
`img` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品图片',
`tag` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品标签',
`location` point NULL COMMENT '发货地经纬度',
`city` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '发货城市',
`originalPrice` decimal(10, 2) NULL DEFAULT NULL COMMENT '原价',
`sellPrice` decimal(10, 2) NULL DEFAULT NULL COMMENT '售价',
`stockNum` int NULL DEFAULT NULL COMMENT '库存',
`createTime` datetime NULL DEFAULT NULL COMMENT '创建时间',
`updateTime` datetime NULL DEFAULT NULL COMMENT '更新时间',
`salesVolume` int NULL DEFAULT NULL COMMENT '销量',
`promotion` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '推广活动',
`category` int NULL DEFAULT NULL COMMENT '商品类别',
`score` decimal(3, 2) NULL DEFAULT NULL COMMENT '商品评分',
`goodComment` int NULL DEFAULT NULL COMMENT '好评数量',
`badComment` int NULL DEFAULT NULL COMMENT '差评数量',
`shopId` int NULL DEFAULT NULL COMMENT '店铺编号',
`shopName` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '店铺名称',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 21001 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
2.2 准备索引
针对搜索数据,创建索引,代码如下:
PUT /product
{
"settings": {
"number_of_shards": 3, //3个主分片
"number_of_replicas": 2, //2个副分片,
"analysis": { //定义分析器
"filter": { //定义过滤器
"pinyin_filter":{ //过滤器的名字
"type":"pinyin", //分词器为拼音类型
"keep_first_letter":true, //保留拼音首字母
"key_full_pinyin":false, //不保留全拼
"keep_none_chinese":true, //结果中保留非中文字母或者数字
"synonyms_path":"mydict/mydict.dict" //指定同义词字典路径
}
},
"analyzer": { //定义分析器
"ik_analyzer_graph":{ //定义一个名为ik_analyzer_graph的分析器
"tokenizer":"ik_smart", //指定分词器
"filter":["lowercase","pinyin_filter"] //指定两个过滤器,其中一个是上面定义的
}
}
}
},
"mappings": {
"properties": {
"id":{ "type": "integer"}, //主键编号
"uid":{ "type": "text"}, //uid
"productName":{ //商品标题
"type": "text",
"analyzer": "ik_analyzer_graph", //使用自定义分词器,
"fields": {"proNameKey":{"type":"keyword"}} //在produceName这个字段建立一个keyword索引类型
},
"tag":{ "type": "keyword"}, //商品标签
"img":{ "type": "text"}, //商品图片
"location":{ "type": "geo_point"}, //发货地址
"city":{ "type": "keyword"}, //卖家所在城市
"originalPrice":{ "type": "double"}, //商品原价
"sellPrice":{ "type": "double"}, //商品销售价
"stockNum":{ "type": "integer"}, //商品库存
"createTime":{ "type": "date", "format": "yyyy-MM-dd HH:mm:ss"}, //创建时间并指定日期格式
"updateTime":{ "type": "date", "format": "yyyy-MM-dd HH:mm:ss"}, //更新时间
"salesVolume":{ "type": "integer"}, //销量
"promotion":{ "type": "keyword"}, //推广活动
"category":{ "type": "integer"}, //分类编号
"score":{ "type": "double"}, //商品评分
"goodComment":{ "type": "integer"}, //好评数量
"badComment":{ "type": "integer"}, //差评数量
"shopId":{ "type": "integer"}, //店铺编号
"shopName":{ "type": "text"} //店铺名称
}
}
}
上面代码的注释都比较全,如果有不清楚的,可以先看看我前面的几篇文章.
2.3 准备数据
Navicat Premium 16有数据生成的功能,可以利用这个功能往数据表里面添加数据,准备1万的数据量进行测试应该是没有问题的,在Navicat生成数据的时候,并不能生成地理位置的数据,可以先留空,然后写一条代码进行更新.代码如下:
UPDATE product_detail
SET `location` = ST_PointFromText(CONCAT('POINT(', 73 + ROUND(RAND()*62,6),' ', 4 + ROUND(RAND()*49,6),')'))
上面这条代码会随机生成经纬度,经纬度范围大概是在我国内部.
2.4 从mysql导入数据
2.4.1 从MySQL中读取数据
先编写对应的实体类,在编写实体类时需要注意date数据类型和point数据类型, date类型需要添加@JsonFormat注解,point类型被拆成两个double类型,具体实体类代码如下:
@Getter
@Setter
@Schema(name = "LocationPoint", description = "发货地点的经纬度")
public class LocationPoint {
@Schema(description = "发货地纬度")
private BigDecimal lat;
@Schema(description = "发货地经度")
private BigDecimal lon;
}
@Getter
@Setter
@TableName("product_detail")
@Schema(name = "ProductDetail", description = "")
public class ProductDetail implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@Schema(description = "UID")
@TableField("uid")
private String uid;
@Schema(description = "商品名称")
@TableField("productName")
private String productName;
@Schema(description = "商品图片")
@TableField("img")
private String img;
@Schema(description = "商品标签")
@TableField("tag")
private String tag;
@Schema(description = "发货地经纬度")
private LocationPoint location;
@Schema(description = "发货城市")
@TableField("city")
private String city;
@Schema(description = "原价")
@TableField("originalPrice")
private BigDecimal originalPrice;
@Schema(description = "售价")
@TableField("sellPrice")
private BigDecimal sellPrice;
@Schema(description = "库存")
@TableField("stockNum")
private Integer stockNum;
@Schema(description = "创建时间")
@TableField("createTime")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@Schema(description = "更新时间")
@TableField("updateTime")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
@Schema(description = "销量")
@TableField("salesVolume")
private Integer salesVolume;
@Schema(description = "推广活动")
@TableField("promotion")
private String promotion;
@Schema(description = "商品类别")
@TableField("category")
private Integer category;
@Schema(description = "商品评分")
@TableField("score")
private BigDecimal score;
@Schema(description = "好评数量")
@TableField("goodComment")
private Integer goodComment;
@Schema(description = "差评数量")
@TableField("badComment")
private Integer badComment;
@Schema(description = "店铺编号")
@TableField("shopId")
private Integer shopId;
@Schema(description = "店铺名称")
@TableField("shopName")
private String shopName;
/**
* 将tag转换为数组
* @return
*/
public String[] getTag(){
if(tag==null){
return null;
}else{
return tag.split(",");
}
}
}
读取数据库的时候,SQL语句如下:
<select id="getAll" resultMap="BaseResultMap">
select ST_X(location) 'stx',ST_Y(location) 'sty',<include refid="Base_Column_List"></include>
from product_detail
</select>
ST_X(经度)对应lon, ST_Y(纬度)对应la t分别读取MySQL中point数据字段的经纬度的值.
2.4.2 将数据写入ES索引
引入依赖:
<!-- 目前java中最新的elasticsearch依赖 restHighLeveClient已经被抛弃-->
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
</dependency>
<!-- 方便进行json与java对象之间的转换-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
创建配置类
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ESClientConfig {
/**
* 创建ES客户端
* @return ES客户端
*/
@Bean
public ElasticsearchClient restHighLevelClient() {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport elasticsearchTransport = new RestClientTransport(restClient,new JacksonJsonpMapper());
return new ElasticsearchClient(elasticsearchTransport);
}
}
从MySQL中读取数据,并将数据写入ES
@Service
public class ProductDetailServiceImpl implements IProductDetailService {
@Resource
private ProductDetailMapper productDetailMapper;
@Resource
ElasticsearchClient esClient;
@Override
public List<ProductDetail> getAll() {
return productDetailMapper.getAll();
}
/**
* 将MySQL中的数据加载到ES索引中
* @return true表示没有出现错误
*/
@Override
public boolean contextLoads() {
boolean result = true;
List<ProductDetail> list = getAll();
BulkRequest.Builder builder = new BulkRequest.Builder().index("product"); // 指定索引
for (ProductDetail product : list) {
builder.operations(op -> op.index(in -> in.id(product.getId().toString()).document(product)));
}
// 运行批量操作
try {
BulkResponse bulk = esClient.bulk(builder.build());
result = !bulk.errors();
} catch (IOException e) {
System.out.println(e.toString());
}
return result;
}
}
2392



被折叠的 条评论
为什么被折叠?



