Bootstrap

快速入门案例实战:电商网站商品管理(一)

内容来自中华石杉在B站的Elasticsearch 顶尖高手系列课程核心知识篇,其中部分代码从 Elasticsearch 5.2 升级到 7.10.1

1. document 数据格式

面向文档的搜索分析引擎

public class Employee {
  private String email;
  private String firstName;
  private String lastName;
  private EmployeeInfo info;
  private Date joinDate;
}

private class EmployeeInfo {  
  private String bio; // 性格
  private Integer age;
  private String[] interests; // 兴趣爱好
}

EmployeeInfo info = new EmployeeInfo();
info.setBio("curious and modest");
info.setAge(30);
info.setInterests(new String[]{"bike", "climb"});

Employee employee = new Employee();
employee.setEmail("zhangsan@sina.com");
employee.setFirstName("san");
employee.setLastName("zhang");
employee.setInfo(info);
employee.setJoinDate(new Date());

employee对象:里面包含了 Employee 类自己的属性,还有一个 EmployeeInfo 对象

两张表:employee 表,employee_info 表,将 employee 对象的数据重新拆开来,变成Employee 数据和 EmployeeInfo 数据

  • employee表:email,firstname,lastname,join_date,4个字段

  • employeeinfo表:bio,age,interests,3个字段;此外还有一个外键字段,比如employeeid,关联着employee表

Elasticsearch 的 document 数据格式(JSON)和数据库的关系型数据格式的区别

{
    "email":      "zhangsan@sina.com",
    "first_name": "san",
    "last_name": "zhang",
    "info": {
        "bio":         "curious and modest",
        "age":         30,
        "interests": [ "bike", "climb" ]
    },
    "join_date": "2017/01/01"
}

2. 电商网站商品管理案例背景介绍

假设有一个电商网站,需要为其基于 Elasticsearch 构建一个后台系统,提供以下功能:

3. 简单的集群管理

Elasticsearch 提供了一套 api,叫做 cat api,可以查看 Elasticsearch中各种各样的数据

GET /_cat/health?v

# 7.10.1
epoch      timestamp cluster           status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1609986928 02:35:28  study-application green           1         1      6   6    0    0        0             0                  -                100.0%

# 5.2
epoch      timestamp cluster       status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1488006741 15:12:21  elasticsearch yellow          1         1      1   1    0    0        1             0                  -                 50.0%

epoch      timestamp cluster       status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1488007113 15:18:33  elasticsearch green           2         2      2   1    0    0        0             0                  -                100.0%

epoch      timestamp cluster       status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1488007216 15:20:16  elasticsearch yellow          1         1      1   1    0    0        1             0                  -                 50.0%

如何快速了解集群的健康状况?green、yellow、red

  • green:每个索引的 primary shard 和 replica shard 都是 active状态的

  • yellow:每个索引的 primary shard 都是 active 状态的,但是部分 replica shard 不是 active 状态,处于不可用的状态

  • red:不是所有索引的 primary shard 都是 active 状态的,部分索引有数据丢失了

为什么现在会处于一个 yellow 状态?

我们现在就一个笔记本电脑,就启动了一个 es 进程,相当于就只有一个 node。现在 es 中有一个 index,就是 kibana 自己内置建立的 index。由于默认的配置是给每个 index 分配 5 个 primary shard 和 5 个 replica shard,而且 primary shard 和 replica shard 不能在同一台机器上(为了容错)。现在 kibana 自己建立的 index 是 1 个primary shard 和 1 个replica shard。当前就一个 node,所以只有 1 个primary shard被分配了和启动了,但是一个replica shard 没有第二台机器去启动。

做一个小实验:此时只要启动第二个 Elasticsearch 进程,就会在 Elasticsearch 集群中有2个node,然后那1个replica shard就会自动分配过去,然后cluster status就会变成green状态。

GET /_cat/indices?v

# 7.10.1
health status index                           uuid                   pri rep docs.count docs.deleted store.size pri.store.size
green  open   .apm-custom-link                -cHKkvF8S_um5DOZUKSZEA   1   0          0            0       208b           208b
green  open   .kibana_task_manager_1          UPJGtaocRaykb09d8QoPoA   1   0          5         3570    420.3kb        420.3kb
green  open   .apm-agent-configuration        yIuKhjPES8O6rATBYWuChA   1   0          0            0       208b           208b
green  open   .kibana-event-log-7.10.1-000001 OEvvbMYIRfacpDICarEBZw   1   0          1            0      5.6kb          5.6kb
green  open   .kibana_1                       D1uIPOjURDquh-msVgkG9Q   1   0         21            2      2.1mb          2.1mb

# 5.2
health status index   uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   .kibana rUm9n9wMRQCCrRDEhqneBg   1   1          1            0      3.1kb          3.1kb

创建索引:PUT /test_index?pretty

PUT /test_index?pretty

{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "test_index"
}

GET _cat/indices?v

# 7.10.1
health status index                           uuid                   pri rep docs.count docs.deleted store.size pri.store.size
...
yellow open   test_index                      X_bJ1tT-TWW-3i-d1Mpy9Q   1   1          0            0       208b           208b

# 5.2 
health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   test_index XmS9DTAtSkSZSwWhhGEKkQ   5   1          0            0       650b           650b
yellow open   .kibana    rUm9n9wMRQCCrRDEhqneBg   1   1          1            0      3.1kb          3.1kb

删除索引:DELETE /test_index?pretty

DELETE /test_index?pretty

{
  "acknowledged" : true
}

  • 新增商品:新增文档,建立索引

PUT /ecommerce/product/1
{
  "name" : "gaolujie yagao",
  "desc" : "gaoxiao meibai",
  "price" : 30,
  "producer" :"gaolujie producer",
  "tags": [ "meibai", "fangzhu" ]
}

#! Deprecation: [types removal] Specifying types in document index requests is deprecated, use the typeless endpoints instead (/{index}/_doc/{id}, /{index}/_doc, or /{index}/_create/{id}).

PUT /ecommerce/_doc/4
{
  "name" : "heiren yagao",
  "desc" : "zhiwu",
  "price" : 50,
  "producer" : "heiren producer",
  "tags": [ "buohe" ]
}

PUT /ecommerce/_doc 
{ 
  "name" : "shuermin yagao", 
  "desc" : "mingan", 
  "price" : 60, 
  "producer" : "shuermin producer", 
  "tags": [ "mingan" ] 
}

{ 
  "error" : "Incorrect HTTP method for uri [/ecommerce/_doc?pretty=true] and method [PUT], allowed: [POST]", 
  "status" : 405 
}

POST /ecommerce/_doc
{
  "name" : "shuermin yagao",
  "desc" : "mingan",
  "price" : 60,
  "producer" : "shuermin producer",
  "tags": [ "mingan" ]
}

POST /ecommerce/_create/6
{
  "name" : "Listerine mouthwash",
  "desc" : "cool mint",
  "price" : 60,
  "producer" : "qiangsheng producer",
  "tags": [ "mint" ]
}

ES 会自动建立 index 和 type,不需要提前创建,而且 es 默认会对 document 每个 field 都建立倒排索引,让其可以被搜索

  • 查询商品:检索文档

GET /ecommerce/product/1

#! Deprecation: [types removal] Specifying types in document get requests is deprecated, use the /{index}/_doc/{id} endpoint instead.

  • 修改商品:替换文档

PUT /ecommerce/_doc/1
{
  "name" : "jiaqiangban gaolujie yagao",
  "desc" :  "gaoxiao meibai",
  "price" : 30,
  "producer" :"gaolujie producer",
  "tags": [ "meibai", "fangzhu" ]
}

替换方式有一个不好,即使必须带上所有的field,才能去进行信息的修改

  • 修改商品:更新文档

POST /ecommerce/_update/1
{
  "doc": {
    "name" : "update post"
  }
}

在执行 POST update 操作的时候,如果内容不变的化,版本是不会增加的。

  • 删除商品:删除文档

DELETE /ecommerce/_doc/1