1、下载安装
ES下载地址:https://www.elastic.co/cn/downloads/past-releases
logStash下载地址:https://www.elastic.co/cn/downloads/past-releases/logstash-7-2-1
安装没啥好说的,直接运行就可以了,需要注意的是如果要使用中文分词(搜索)需要添加中文分词插件(其中的v6.3.0这些版本号需要改成与自己es版本对应的)
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.3.0/elasticsearch-analysis-ik-6.3.0.zip
2、es服务起来之后(默认端口9200),使用postman通过restful请求api的方式完成index创建
method:PUT
URL:http://127.0.0.1:9200/druginfo
body的json:
{"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
}}
设置字段type类型为keyWord(因为我的搜索目的是这几个字段类似于sql语句中的like)
method:PUT
URL: http://127.0.0.1:9200/druginfo/_mapping
body的json:
{
"properties": {
"brand": {
"type": "keyword"
},
"manufacture": {
"type": "keyword"
},
"generic_name": {
"type": "keyword"
}
}
}
在这里我是设置的keyWord,如果要使用中文分词支持全文搜索则是(url和method同上)
{
"properties": {
"brand": {
"analyzer": "ik_smart",
"search_analyzer": "ik_smart",
"type": "text"
},
"generic_name": {
"analyzer": "ik_smart",
"search_analyzer": "ik_smart",
"type": "text"
}
}
}
3、通过logstash将mysql数据库中的数据导入到es中
a:需要将mysql驱动程序包放在lib文件下(后续配置文件中需要指定位置)
b:新增logstash-mysql.conf配置文件,配置文件内容如下
input {
stdin {
}
jdbc {
# 数据库 数据库名称为erp_server_db,表名为yjc_drug_base_info
jdbc_connection_string => "jdbc:mysql://127.0.0.1:3306/erp_server_db?characterEncoding=utf8&serverTimezone=GMT%2b8"
# 用户名密码
jdbc_user => "root"
jdbc_password => "123456"
# jar包的位置
jdbc_driver_library => "../lib/mysql-connector-java-8.0.13.jar"
# mysql的Driver
jdbc_driver_class => "com.mysql.jdbc.Driver"
jdbc_paging_enabled => "true"
jdbc_page_size => "50000"
statement => "select * from yjc_drug_base_info"
schedule => "* * * * *"
}
}
filter {
json {
source => "message"
remove_field => ["message"]
}
}
output {
elasticsearch {
hosts => "127.0.0.1:9200"
# index名
index => "druginfo"
# 需要关联的数据库中有有一个id字段,对应索引的id号
document_id => "%{id}"
}
stdout {
codec => json_lines
}
}
c:在当前bin目录下执行.\logstash -f .\logstash-mysql.conf命令进行数据导入

4、进行数据查询
数据导入es之后,可以开始查询了,具体查询命令参考 https://n3xtchen.github.io/n3xtchen/elasticsearch/2017/07/05/elasticsearch-23-useful-query-example
我这里只是针对我需要实现的功能给出效果和例子。我想要实现的是传入一个字符串,返回生产厂家或者通用名包含这个字符串的查询结果。
method: POST
url:http://127.0.0.1:9200/druginfo/_search?pretty
body里的json:
{
"query": {
"bool": {
"minimum_should_match": 1,
"should": [
{
"wildcard": {
"manufacture": "*妇科养血颗粒*"
}
},
{
"wildcard": {
"generic_name": "*妇科养血颗粒*"
}
}
]
}
}
}
查询结果如下

浙公网安备 33010602011771号