引言

温馨提示:

准备工作

bitnami/elasticsearch:7 容器的安装

安装的docker-compose.yml文化如下

version: '3'

services:
  elasticsearch:
    container_name: elasticmy
    image: docker.io/bitnami/elasticsearch:7
    ports:
      - '9200:9200'
      - '9300:9300'
    volumes:
      - './elasticsearch_data:/bitnami/elasticsearch/data'
volumes:
  elastic3:
    driver: local

容器启动方式:

docker-compose up -d

如果容器无法正常启动,则可能需要给宿主主机的elastic_data目录赋予权限

chmod 777 elasticsearch_data
  • 为elasticsearch安装安装中文分词器插件
  1. 以root身份进入到elasticsearch容器中
docker exec -u root -it elasticmy bash
  1. 进入容器后,在容器的/bin目录下执行安装分词器插件命令
elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.17.3/elasticsearch-analysis-ik-7.17.3.zip
  1. 安装完毕后重启elasticsearch容器,至此elasticsearch的分词器插件就安装完毕了😄
docker restart elasticmy
在elasticsearch中创建对应的索引
## 这里的索引名称我和MySQL中对应的数据库名称同名
## 使用include_type_name 是为了可以预先自定义索引的_type,不自定义的话,elasticsearch
## 会默认生成名称为_doc的_type
PUT  myblog?include_type_name=true  
{
    "mappings": {
        "t_article": {  // 自定义的_type,这里我选择其名称和数据库要同步的表名相同
            "properties": {
                "article_content": {// 为文档中的article_content字段设置分词器
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "fielddata": true
                },
                "article_title": {// 为文档中的article_title字段设置分词器
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "fielddata": true
                }
            }
        }
    }
}
  • 使用go-mysql-elasticsearchs实时同步MySQL中myBlog数据库中的t_article表中的数据到elasticsearch中
  1. 先拉取go-mysql-elasticsearch的代码
git clone https://github.com/go-mysql-org/go-mysql-elasticsearch.git
  1. 进入代码的根目录对代码进行编译
make
  1. 编译成功后会在代码根目录下的bin目录下生成go-mysq-elasticsearch的可执行程序:

在这里插入图片描述

[[rule]]
schema = "myBlog"// 要同步的数据库名称
table = "t_article" // 要同步的数据库表
index = "myBlog" // 同步到elasticsearch中的索引名称
type = "t_article" // 同步到elasticsearch中的_type名称

在这里插入图片描述

进行数据的高亮搜索

  1. 进行高亮搜索
GET  myblog/_search

{
    "query": {
        "bool": {
            "should": [
                {
                    "multi_match": {
                        "query": "加锁",//搜索的关键词
                        "fields": [ // 要进行搜索的字段
                            "article_content",
                            "article_title"
                        ]
                    }
                }
            ],
            "minimum_should_match": 1
        }
    },
    "highlight": {
        "fields": {
            "article_content": {},//高亮的字段
            "article_title": {}//高亮的字段
        },
        "pre_tags": "<span style=\"color: red\">", //高亮左标记
        "post_tags": "</span>" // 高亮右标记
    }
}
  1. 高亮且分词的搜索结果