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": "*婦科養血顆粒*" } } ] } } }
查詢結果如下