【Elasticsearch】ElasticSearch的基本使用

1. 索引基本操作

GET /_cat/indices?v            //查看索引
PUT /products                  //创建名为 products 的索引
DELETE /products               //删除名为 products 的索引

//使用json格式创建一个索引
PUT /orders
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  }
}

2. 映射的基本操作

2.1创建映射

#创建商品索引 prducts 指定 mapping(映射) {id, title, price, created_at, description(描述)}
PUT /products
{
  "settings": {
    "number_of_replicas": 0,
    "number_of_shards": 1
  },
  "mappings":{
    "properties": {
      "id":{
        "type":"integer"
      },
      "title":{
        "type":"keyword"
      },
      "price":{
        "type":"double"
      },
      "created_at":{
        "type":"date"
      },
      "description": {
        "type":"text"
      }      
    }
  }
}

2.2查看索引的映射信息

GET /products/_mapping

3. 文档操作

3.1文档添加

#添加文档内容,手动添加文档id
POST /products/_doc/1
{
  "id":1,
  "title":"小浣熊",
  "price":0.5,
  "create_at":"2012-11-12",
  "description":"小浣熊真好吃"
}

#添加文档内容 自动创建文档id
POST /products/_doc/
{
  "title":"日本豆",
  "price":0.5,
  "create_at":"2012-11-12",
  "description":"日本豆真不错"
}

3.2文档查询

GET /products/_doc/1      //基于文档id删除

3.3删除文档

DELETE /products/_doc/1  //基于文档id删除

3.4更新文档

#更新文档 (删除原有文档,后重新添加) 
PUT /products/_doc/1
{
  "title":"小小浣熊",
  "price":0.5,
  "create_at":"2012-11-12",
  "description":"小浣熊真好吃"
}	
#更新文档 (指定字段进行更新)
POST /products/_doc/1/_update
{
  "doc":{
    "price":1.6
  }
}

3.5文档的批量操作

#文档的批量操作 _bluk
POST /products/_doc/_bulk
{"index":{"_id":2}}      //插入
  { "id":2,"title":"巴豆", "price":1.3,"create_at":"2012-11-12","description":"巴豆真好吃"}
{"index":{"_id":3}}      //插入
  {"id":3,"title":"乌龟","price":1.4,"create_at":"2012-11-12","description":"乌龟真好吃"}
{"update":{"_id":1}}     //更新
  {"doc":{"title":"小夯"}}
{"delete":{"_id":2}}     //删除

必须将文档内容放在同一行,不允许换行

批量操作并非原子性操作,并不会因为一条语句不成立则终止

4. 高级查询 (Query DSL)

4.1查询所有文档

match_all关键字:返回索引中的全部文档

# GET /索引名/_doc/_search {json格式请求数据}
# GET /索引名/_search {json格式请求数据}  可以不加_doc
# query DSL 语法查询所有 match_all
GET /products/_doc/_search 
{
  "query":{
    "match_all":{}
  }
}

4.2关键词进行查询

term关键字:用来使用关键字查询

# term 基于关键词查询
# `keyword`  `integer` `double` `date` 类型日后搜索使用全部内容搜索 不分词
# text 类型 默认使用标准分词器对中文进行单字分词 对英文进行单词分词
GET /products/_search
{
  "query": {
    "term":{
      "title":{
        "value":"乌龟"
      }
    }
  }
}
  1. 在 Es中除了 text 类型分词其余类型均不分词
  2. 在 Es中默认使用标准分词器 中文单字分词 英文单词分词

4.3范围查询

range关键字:用来指定查询指定范围内的文档

#范围查询 ranger
GET /products/_search
{
  "query": {
    "range": {
      "price":{
        "gte":0,
        "lte":5
      }
    }
  }
}

4.4前缀查询

prefix关键字: 用来检索含有指定前缀关键字的相关文档

# 前缀查询
GET /products/_search 
{
  "query":{
    "prefix": {
      "title": {
        "value": "小"
      }
    }
  }
}

4.5通配符查询

wildcard 关键字 通配符查询 ?用来匹配一个任意字符 *用来匹配多个任意字符

#wildcard 通配符查询 ? 匹配一个字符 *匹配多个字符
GET /products/_search  
{
  "query":{
    "wildcard": {
      "description": {
        "value": "wu*"
      }
    }
  }
}

4.6多id查询

ids 关键字: 值为数组类型,用来根据一组id获得多个文文档

GET /products/_search 
{
  "query":{
    "ids":{
      "values":[1, 3, 5]
    }
  }
}

4.7模糊查询

fuzzy 关键字:用来模糊查询含有指定关键字的文档,搜索关键字可以一定程度与真实值不一致

  • 搜索关键字长度小于 2 不允许出现模糊
  • 搜素关键字长度为3 - 5 允许出现一次模糊
  • 搜索关键字长度大于5 允许出现两次模糊
# fuzzy 模糊查询
GET /products/_search
{
  "query": {
    "fuzzy":{
      "title": "乌龟腐"
    }
  }
}

4.8bool查询

bool 关键字: 用来组合多个条件实现的复杂查询

  • must:相当于&&同时成立
  • should: 相当于||成立一个就行
  • must_not:相当于! 不能满足任何一个
GET /products/_search 
{
  "query": {
    "bool": {
      "should" :[
        {
          "ids": {
            "values": [3]
          }
        },{
          "term": {
            "title": {
              "value": "豪猪"
            }
          }
        }
      ]
    }
  }
}

4.9多字段查询

multi_match : 字段类型分词,将查询条件分词之后进行查询修改字段,如果该字段不分词就会将查询条件作为整体进行查询

# multi_match
#多字段查询,用的很多很重要
# 注意: query 输入关键词 输入一段文本
GET /products/_search
{
  "query": {
    "multi_match": {
      "query": "豪龟",
      "fields": ["title", "description"]
    }
  }
}

4.10默认字段分词查询

query_string :查询字段分词就讲查询条件分词查询 查询字段不分词将查询条件不分词查询

GET /products/_search 
{
  "query": {
    "query_string": {
      "default_field": "description",
      "query": "豪龟"
    }
  }
 }

4.11高亮查询

highlight 关键字: 可以让符合条件的文档中的关键字高亮,该字段必须是可以分词的。并且高亮并没有修改原始文档,而是将高亮的字段放到一个新的字段中

# 只有可以分词的字段才可以调整高亮
GET /products/_search 
{
  "query": {
    "query_string": {
      "default_field": "description",
      "query": "豪龟"
    }
  },
  "highlight": {
    "pre_tags": ["<span style='color:red;'>"],       //自定义高亮标签
    "post_tags": ["</span>"],
    "require_field_match": "false",     //关闭高亮字段的验证,全部字段都可以高亮
    "fields": {
      "*":{}
    }
  }
}

4.12返回指定条数

size 关键字:控制返回文档页数,默认10条

# 只有可以分词的字段才可以调整高亮
GET /products/_search 
{
  "query": {
    "query_string": {
      "default_field": "description",
      "query": "豪龟"
    }
  },
  "highlight": {
    "pre_tags": ["<span style='color:red;'>"], 
    "post_tags": ["</span>"],
    "require_field_match": "false", 
    "fields": {
      "*":{}
    }
  },
  "size":3  //添加size 字段则最多返回三条
}

4.13分页查询

from 关键字:用来指定起始返回未知,和size关键字连用可以实现分页效果

# 只有可以分词的字段才可以调整高亮
GET /products/_search 
{
  "query": {
    "query_string": {
      "default_field": "description",
      "query": "豪龟"
    }
  },
  "highlight": {
    "pre_tags": ["<span style='color:red;'>"], 
    "post_tags": ["</span>"],
    "require_field_match": "false", 
    "fields": {
      "*":{}
    }
  }, 
  "from": 0,           //从0开始返回3条,若还想要将from 改成3,则会从第三条开始再返回三条
  "size": 3
}

4.14指定字段进行排序

sort 关键字: 指定字段进行排序 desc是降序asc是升序,当我们进行排序输出时会干预每个文档的默认得分

# 只有可以分词的字段才可以调整高亮
GET /products/_search 
{
  "query": {
    "query_string": {
      "default_field": "description",
      "query": "豪龟小浣熊巴豆"
    }
  },
  "highlight": {
    "pre_tags": ["<span style='color:red;'>"], 
    "post_tags": ["</span>"],
    "require_field_match": "false", 
    "fields": {
      "*":{}
    }
  },
  "from": 0,
  "size": 3,
  "sort": [
    {
      "price":{
        "order": "desc"
      }
    }
  ]
}

4.15返回指定字段

_source关键字:是一个数组,在数组中用来指定展示哪些字段

# 只有可以分词的字段才可以调整高亮
GET /products/_search 
{
  "query": {
    "query_string": {
      "default_field": "description",
      "query": "豪龟小浣熊巴豆"
    }
  },
  "highlight": {
    "pre_tags": ["<span style='color:red;'>"], 
    "post_tags": ["</span>"],
    "require_field_match": "false", 
    "fields": {
      "*":{}
    }
  },
  "from": 0,
  "size": 3,
  "sort": [
    {
      "price":{
        "order": "desc"
      }
    }
  ],
  "_source": ["id", "title", "description"]
}

5. 分词器

5.1Analysis(文本分析) 和 Analyzer(文本分词)

Analysis: 文本分析是把全文本转换成一系列的单词(term/token)的过程,也叫分词(Analyzer).Analysis是通过Analyzer来实现的。分词就是将文档通过Analyzer分成一个个的Term,每一个Term都指向包含这个Term的文档

分析器由三种构建组成: character filters(0 或 多), tokenizers, token filters(0或多)

  • character filter字符过滤器: 在一段文本分此前进行预处理,最常见的就是过滤html标签
  • tokenizers分词器: 英文分词可以根据空格将单词分开,中文单词使用机器学习算法进行切分
  • Token filters Token过滤器:将切分的单词进行加工(如大小写转换,去掉停用词,假如同义词等)

5.2内置分词器

  • Standard Analyzer - 默认分词器,英文单词词切分,过滤标点符号,并且小写处理
  • Simple Analyzer - 按照单词切分(符号被过滤), 小写处理,中文按照空格分词
  • Stop Analyzer - 小写处理,停用词过滤(the, a, is)
  • Whitespace Analyzer - 按照空格切分,不转化小写,不去掉标点符号
  • Keyword Analyzer - 不分词, 直接将输入当作输出
# 创建索引时显示指定分词器
PUT /test 
{
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "standard"
      }
    }
  }
}
# 手动插入一个id=1 的文档
PUT /test/_doc/1
{
  "title": "我是小黑,this is good Man"
}
# 查找good
GET /test/_search 
{
  "query": {
    "term": {
      "title": {
        "value": "good"
      }
    }
  }
}


6. IK分词器

ik_smartik_max_word两种模式,前者切分力度比较粗而后者比较细

//初步检测IK分词器
POST /_analyze 
{
  "analyzer": "ik_max_word",
  "text": "中华人民共和国国歌"
}

POST /_analyze 
{
  "analyzer": "ik_max_word",
  "text": "中华人民共和国国歌"
}


# 创建索引时显示指定IK分词器
PUT /test 
{
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}
DELETE /test

DELETE /test/_doc/1

# 手动插入一个id=1 的文档
PUT /test/_doc/1
{
  "title": "今天是中华人民共和国成立100周年,应该放中华人民共和国国歌"
}
# 查找good
GET /test/_search 
{
  "query": {
    "term": {
      "title": {
        "value": "国歌"
      }
    }
  }
}

扩展词、停用词配置

  • 扩展词典 就是有些词并不是关键词,但我们也希望被ES当作用来检索的关键词,可以将这些词加入扩展词典
  • 停用词典 就是有些词是关键字,但是出于业务场景我们不想使用这些关键词进行检索,可以将这些词放到停用词典中

定义扩展词典和停用词典可以修改IK分词器中的config目录中的IKAnalyzer.cfg.xml这个文件,我们还可以发现config目录下已经有很多处理好的词典等待我们添加

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>IK Analyzer 扩展配置</comment>
	<!--用户可以在这里配置自己的扩展字典 -->
	<entry key="ext_dict">ext.dic</entry>           
	 <!--用户可以在这里配置自己的扩展停止词字典-->
	<entry key="ext_stopwords"></entry>
	<!--用户可以在这里配置远程扩展字典 -->
	<!-- <entry key="remote_ext_dict">words_location</entry> -->
	<!--用户可以在这里配置远程扩展停止词字典-->
	<!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>

7. Filter Query

过滤查询会筛选出符合的文档,并不计算得分,而且它还可以缓存文档。从性能上考虑,过滤比查询更快。过滤适合在大范围筛选数据,而查询适合精确匹配数据,一般应用时,需要先使用过滤操作进行过滤数据,然后使用查询匹配数据

8.Search_engine 的实现

binlog技术实现MySQLelasticsearch 进行同步

binlog数据库二进制日志文件,存储关于数据库增删改查操作

9. binlog设置

# 查看log_bin 是否开启 并查看其存储路径
mysql> show variables like 'log_%';
# MYSQL日志存储路径
F:\MySQLData\MySQL\MySQL Server 8.0\Data\LAPTOP-GOSMC21V-bin 
# 再次查看设置
mysql> show global variables like "%binlog%";
# 修改binlog_format 变量值为Row
mysql> set global binlog_format="ROW";

10.python 读取 binlog数据

安装模块

PS F:\search\project1> pip install mysql-replication
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
    WriteRowsEvent,
    UpdateRowsEvent,
    DeleteRowsEvent
)

MYSQL_SETTINGS={
    "host": "localhost",
    "user": "root",
    # 这里还需填写密码信息
}
stream=BinLogStreamReader(connection_settings=MYSQL_SETTINGS,
                          server_id=4,
                          blocking=True,
                          only_schemas="readerbinlog",
                          only_events=[WriteRowsEvent, UpdateRowsEvent, DeleteRowsEvent])
# for debug
print(stream)
for binlogstream in stream:
    for row in binlogstream.rows:
        print(row)
        print ("============")

11.MySQL信息同步到Elasticsearch

使用Kafka页面缓存和顺序读写

页面缓存技术 + 磁盘顺序读写 高效实现消息队列的处理

下载 zookeeper

conf 路径下有一个zoo_sample.cfg 将其拷贝一份重命名为 zoo.cfg
dataDir=/tmp/zookeeper 

安装kafka

进入 kafka_2.11-2.0.0 文件夹
执行 .\bin\windows\kafka-server-start.bat .\config\server.properties

使用python模块来实现kafka生产者和消费者模型

安装python 调用kafka模块

pip install kafka-python

同步

  • mysql中的数据首先会存储在elasticsearch
    • python 读取 mysql 数据
    • 将读取的数据存储到elasticsearch
  • mysql中的数据发生变化,同时elasticsearch中的数据也要发生变化
    • 数据库执行插入,elasticsearch 也要插入
    • 数据库执行更新, elasticsearch也要插入
    • 数据库执行删除, elasticsearch也要删除
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白在进击

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值