FILEBEAT+ELK日志收集平台搭建流程

时间:2024-05-25 23:05:38

filebeat+elk日志收集平台搭建流程

1、         整体简介:

模式:单机

平台:Linux - centos - 7

ELK:elasticsearch、logstash、kibana三款开源软件的集合。

FILEBEAT:代替logstash的采集功能,轻量、耗用小。

目前收集的有nginx日志、java日志[单行|多行]。

都是通过在客户端的生成日志配置文件中定义好初步json格式,然后利用filebeat采集到logstash,存储到elasticsearch,最后通过kibana在浏览器页面中展示出来。

elasticsearch、logstash、kibana 如果是root安装,默认会创建(elasticsearch、logstash、kibana)三个单独用户来独立运行。用www用户安装好后默认是以www用户运行。本文演示用的是www。

2、         软件环境安装:

(1)、java环境:

Elasticsearch需要安装Java 8的环境。

如果没有下载jdk1.8的软件包,可以直接安装 java-1.8.0-openjdk。

(2)、下载elasticsearch(Linux版本)的二进制包并解压:

$ wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.4.0.tar.gz

$ unzip elasticsearch-6.4.0.tar.gz

$ mv elasticsearch-6.4.0 elasticsearch

$ vim elasticsearch/config/elasticsearch.yml

path.data: /data/soft/elasticsearch/data/

path.logs: /data/soft/elasticsearch/logs/

$ sudo sysctl -w vm.max_map_count=262144

$ vim /etc/sysctl.conf文件,添加:

vm.max_map_count=262144

$ sysctl -p

$ vim /etc/security/limits.conf文件,末尾添加:

*  soft    nproc        20536

*  hard   nproc        20536

*  soft    nofile        65536

*  hard   nofile        65536

退出重新登录生效。

将elasticsearch、logstash、kibana、filebeat的bin目录加入到环境变量PATH:

/data/soft/logstash/bin:/data/soft/kibana/bin:/data

/soft/elasticsearch/bin:/data/soft/filebeat
$ nohup elasticsearch -d >/data/soft/elasticsearch/nohup.out
2>&1 &

启动后,Elastic默认在9200端口运行。

$ curl -X GET localhost:9200或curl localhost:9200

{

"name" : "zny0iRv",

"cluster_name" : "elasticsearch",

"cluster_uuid" : "AErImFrFQOaoFPzNSdVmfA",

"version" : {

"number" : "6.4.0",

"build_flavor" : "default",

"build_type" : "tar",

"build_hash" : "595516e",

"build_date" : "2018-08-17T23:18:47.308994Z",

"build_snapshot" : false,

"lucene_version" : "7.4.0",

"minimum_wire_compatibility_version" : "5.6.0",

"minimum_index_compatibility_version" : "5.0.0"

},

"tagline" : "You Know, for Search"

}

(3)、下载logstash(Linux版本)的二进制包并解压:

$ wget https://artifacts.elastic.co/downloads/logstash/logstash-6.4.0.zip

$ unzip logstash-6.4.0.zip logstash-6.4.0

$ mv logstash-6.4.0 logstash

$ cd logstash/config/

$ cat config/logstash.yml|grep -vE
'^$|#'

# pipeline 线程数,可优化为 ---> pipeline.workers: CPU内核数(或几倍cpu内核数)

pipeline.workers:
32

# 实际output 时的线程数,可优化为 ---> pipeline.output.workers: 不超过pipeline 线程数

pipeline.output.workers:
32

# 每次发送的事件数

pipeline.batch.size:
8000

#  发送延时

pipeline.batch.delay:
15

# filter设置multiline后,pipline worker会自动将为1,如果使用filebeat,建议在beat中就使用multiline,如果使用logstash作为shipper,建议在input 中设置multiline,不要在filter中设置multiline。

$ vim logstash.conf

input {

beats {

codec => json

port => 5044

#host => “0.0.0.0”

}

}

filter
{

mutate {

remove_field =>
["@version","[beat][name]","[beat][version]","[beat][hostname]","tags"]

#remove_field => "message"

}

if [nx_upstream_host] != "-" {

mutate {

convert =>
{"nx_upstream_response_time"=>"float"}

convert =>
{"nx_upstream_response_length"=>"integer"}

convert =>
{"nx_upstream_connect_time"=>"float"}

}

} else {

mutate {

remove_field =>
["nx_upstream_host","nx_upstream_response_time","nx_upstream_response_length","nx_upstream_status","nx_upstream_connect_time"]

}

}

}

output
{

# 8bet-test-srv-4:nginx

if [project] == "8bet-admin" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"8bet-nginx-admin-%{+YYYY.MM.dd}"

}

} else if [project] == "8bet-h5"
{

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"8bet-nginx-h5-%{+YYYY.MM.dd}"

}

} else if [project] ==
"8bet-newadmin" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"8bet-nginx-newadmin-%{+YYYY.MM.dd}"

}

} else if [project] ==
"8bet-newh5" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"8bet-nginx-newh5-%{+YYYY.MM.dd}"

}

} else if [project] ==
"8bet-nginx-error" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"8bet-nginx-error-%{+YYYY.MM.dd}"

}

# 8bet-test-srv-5:nginx

} else if [project] ==
"pay-nginx-admin" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"pay-nginx-admin-%{+YYYY.MM.dd}"

}

} else if [project] ==
"pay-nginx-user" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"pay-nginx-user-%{+YYYY.MM.dd}"

}

} else if [project] ==
"pay-nginx-api" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"pay-nginx-api-%{+YYYY.MM.dd}"

}

} else if [project] ==
"pay-nginx-error" {

elasticsearch {

hosts =>
["http://localhost:9200"]

index =>
"pay-nginx-error-%{+YYYY.MM.dd}"

}

# 8bet-test-srv-4:java

} else if [source] ==
"/log/billing/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-billing-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/billing/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-billing-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/member/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-member-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/member/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-member-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/admin/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-admin-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/admin/error.log" {

elasticsearch {

hosts => ["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-admin-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/pay/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-pay-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/pay/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-pay-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/discount/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-discount-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/discount/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-discount-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/schedule/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-schedule-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/schedule/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-schedule-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/security/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-security-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/security/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-security-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/caipiao/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-caipiao-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/caipiao/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-caipiao-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/cpbilling/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-cpbilling-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/cpbilling/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-cpbilling-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/cpmessage/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-cpmessage-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/cpmessage/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-cpmessage-error-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/cpschedule/info.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-cpschedule-info-%{+YYYY.MM.dd}"

}

} else if [source] ==
"/log/cpschedule/error.log" {

elasticsearch {

hosts =>
["http://localhost:9200"]

#manage_template => true

#template_overwrite => true

index =>
"8bet-java-cpschedule-error-%{+YYYY.MM.dd}"

}

}

stdout {

codec => rubydebug

}

}

#output
{

#  stdout { codec => rubydebug }

#  elasticsearch {

#    hosts =>
["http://localhost:9200"]

#    index =>
"%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM}"

#  }

#}

检查logstash配置文件的语法命令:

$ logstash --path.settings /data/soft/logstash/config/ -f
/data/soft/logstash/config/logstash.conf -t

$ nohup logstash -f
/data/soft/logstash/config/logstash.conf >/data/soft/logstash/out.log
2>&1 &

(4)、下载kibana(Linux版本)的二进制包并解压:

$ wget https://artifacts.elastic.co/downloads/kibana/kibana-6.4.0-linux-x86_64.tar.gz

$ tar -zxf kibana-6.4.0-linux-x86_64.tar.gz

$ mv kibana-6.4.0-linux-x86_64 kibana

$ vim kibana/config/kibana.yml

elasticsearch.url:
"http://localhost:9200"

elasticsearch.shardTimeout:
0

pid.file: /data/soft/kibana/kibana.pid

$ nohup /data/soft/kibana/bin/kibana
>/data/soft/kibana/out.log 2>&1 &

3、        
FILEBEAT(收集端)单独配置:

以一台filebeat采集端做示例:

(1)、nginx日志格式配置:

$ vim
/data/soft/nginx/conf/nginx.conf

user www;

worker_processes  4;

worker_rlimit_nofile
20000;

worker_cpu_affinity
00000001 00000010 00000100 00001000;

error_log
/log/nginx/error.log error;

pid       /log/nginx/nginx.pid;

events
{

use epoll;

worker_connections  20000;

}

http {

include       mime.types;

default_type  application/octet-stream;

sendfile        on;

tcp_nodelay     on;

tcp_nopush     on;

client_body_timeout 10;

client_header_timeout 10;

send_timeout 10;

keepalive_timeout  50;

client_body_buffer_size  4k;

client_header_buffer_size 1k;

client_max_body_size 10m;

large_client_header_buffers 2 1k;

open_file_cache max=65535 inactive=20s;

open_file_cache_valid 30s;

open_file_cache_min_uses 1;

gzip on;

gzip_min_length 1k;

gzip_buffers 8 16k;

gzip_comp_level 3;

gzip_http_version 1.1;

gzip_disable "MSIE [1-6].";

gzip_types text/plain
application/x-javascript text/css application/xml application/x-httpd-php
image/jpeg image/gif image/png;

gzip_vary on;

#
nginx
需要配置的日志输出格式为json格式:代替logstashgrok过滤。

log_format main
'{"nx_localtime@timestamp":"$time_local",'

'"nx_host":"$server_addr",'

'"nx_client_ip":"$remote_addr",'

'"nx_body_size":$body_bytes_sent,'

'"nx_request_time":$request_time,'

'"nx_scheme":"$scheme",'

'"nx_http_host":"$host",'

'"nx_request_method":"$request_method",'

'"nx_uri":"$uri",'

'"nx_status":"$status",'

'"nx_referer":"$http_referer",'

'"nx_agent":"$http_user_agent",'

'"nx_upstream_host":"$upstream_addr",'

'"nx_upstream_response_time":"$upstream_response_time",'

'"nx_upstream_response_length":"$upstream_response_length",'

'"nx_upstream_status":"$upstream_status",'

'"nx_upstream_connect_time":"$upstream_connect_time"}';

include vhost/*.conf;

}

访问nginx,查看此时nginx-log中的输出:

{"nx_localtime@timestamp":"27/Sep/2018:21:37:17
+0800","nx_host":"156.237.192.218","nx_client_ip":"113.61.62.154","nx_body_size":665,"nx_request_time":0.000,"nx_scheme":"http","nx_http_host":"log.2481888.com","nx_request_method":"GET","nx_uri":"/nginx/","nx_status":"200","nx_referer":"http://log.2481888.com/","nx_agent":"Mozilla/5.0
(Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/69.0.3497.100
Safari/537.36","nx_upstream_host":"","nx_upstream_response_time":"","nx_upstream_response_length":"","nx_upstream_status":"","nx_upstream_connect_time":""}

(2)、java日志格式配置:

利用spring cloud config配置中心的集中化管理java日志输出,修改统一的配置文件:

$ vim /data/www/java/log4j2.xml

<configuration
status="INFO">

<!-- 参数配置 -->

<properties>

<property
name="app_name">${sys:project.name}</property>

<property
name="log_path">/log/${app_name}</property>

<!-- 文件输出格式配成json格式,方便filebeat收集,省略logsta过滤 -->

<property
name="PATTERN">{"jv_time":"%d{yyyy-MM-dd
HH:mm:ss.SSS}","jv_level":"%level","jv_thread":"%thread","jv_class":"%logger","jv_method":"%M","jv_message":"%replace{%replace{%msg}{"}{\\"}}{\n}{|}","jv_throwable":"%replace{%replace{%xEx}{"}{\\"}}{[\n\r\t]}{|}"}%n{%xEx}{none}</property>

</properties>

<appenders>

...

...

重启java项目后,此时日志中的输出就变成json格式了。

{"jv_time":
"2018 09 29 20:16:32.672","jv_level":
"INFO","jv_thread":
"MQClientFactoryScheduledThread", "jv_class":
"RocketmqClient", "jv_method":
"sendHeartbeatToAllBroker","jv_message": "send heart
beat to broker[broker-a 0 8bet-test-srv-2:10911]
success","jv_throwable": ""}

(3)、filebeat的安装与配置:

$wget https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.4.0-linux-x86_64.tar.gz

$
tar -zxf filebeat-6.4.0-linux-x86_64.tar.gz

$ mv filebeat-6.4.0-linux-x86_64 filebeat

$ vim filebeat/filebeat.yml

filebeat.inputs:

- type:
log

paths:

- /log/nginx/8bet.admin.log

fields:

project: 8bet-admin

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: nginx

fields_under_root: true

- type:
log

paths:

- /log/nginx/8bet.h5.log

fields:

project: 8bet-h5

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: nginx

fields_under_root: true

- type:
log

paths:

- /log/nginx/8bet.newadmin.log

fields:

project: 8bet-newadmin

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: nginx

fields_under_root: true

- type:
log

paths:

- /log/nginx/8bet.newh5.log

fields:

project: 8bet-newh5

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: nginx

fields_under_root: true

- type:
log

paths:

- /log/nginx/error.log

fields:

project: 8bet-nginx-error

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: nginx

fields_under_root: true

- type:
log

paths:

- /log/billing/info.log

fields:

project: 8bet-java-billing

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/billing/error.log

fields:

project: 8bet-java-billing

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

#error日志多行可配置项

#  multiline.pattern: '^\{'

#  multiline.negate: true

#  multiline.match: after

- type:
log

paths:

- /log/member/info.log

fields:

project: 8bet-java-member

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/member/error.log

fields:

project: 8bet-java-member

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/admin/info.log

fields:

project: 8bet-java-admin

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/admin/error.log

fields:

project: 8bet-java-admin

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/pay/info.log

fields:

project: 8bet-java-pay

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/pay/error.log

fields:

project: 8bet-java-pay

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/discount/info.log

fields:

project: 8bet-java-discount

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/discount/error.log

fields:

project: 8bet-java-discount

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/schedule/info.log

fields:

project: 8bet-java-schedule

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/schedule/error.log

fields:

project: 8bet-java-schedule

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/security/info.log

fields:

project: 8bet-java-security

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/security/error.log

fields:

project: 8bet-java-security

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/caipiao/info.log

fields:

project: 8bet-java-caipiao

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/caipiao/error.log

fields:

project: 8bet-java-caipiao

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/cpbilling/info.log

fields:

project: 8bet-java-cpbilling

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/cpbilling/error.log

fields:

project: 8bet-java-cpbilling

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/cpmessage/info.log

fields:

project: 8bet-java-cpmessage

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/cpmessage/error.log

fields:

project: 8bet-java-cpmessage

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/cpschedule/info.log

fields:

project: 8bet-java-cpschedule

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

- type:
log

paths:

- /log/cpschedule/error.log

fields:

project: 8bet-java-cpschedule

server_ip: 192.168.41.4

server_name: 8bet-test-srv-4

soft: java

fields_under_root: true

filebeat.config.modules:

path: ${path.config}/modules.d/*.yml

reload.enabled: false

setup.template.settings:

index.number_of_shards: 3

setup.kibana:

output.logstash:

hosts: ["8bet-test-srv-6:5044"]

启动:

$ /data/soft/filebeat/filebeat
-c /data/soft/filebeat/filebeat.yml
&

PS:最后将elk和filebeat的相关命令写入到启动脚本简化操作。

4、        
REST API方式操作:

常用的几种操作示例:

$ curl -XGET 'localhost:9200/_cat/health?v&pretty=true'

$ curl -XPUT
'localhost:9200/laptops'

$curl -XPUT
'localhost:9200/laptops/doc/1?pretty&pretty' -H 'Content-Type:
application/json' -d ‘{ "title": "Laptop X1 i7 8gb RAM " }’

$curl -XPUT
'localhost:9200/laptops/doc/2?pretty&pretty' -H 'Content-Type:
application/json' -d ‘{ "title": "Laptop X2 i5 4gb RAM " }’

$ curl -XGET
'localhost:9200/laptops/_search?pretty=true' -H 'Content-Type:
application/json'

$ curl -XDELETE
'localhost:9200/laptops/?pretty=true'

5、          附录图片

filebeat发送字段:

FILEBEAT+ELK日志收集平台搭建流程

6、          以下部分为摘录网上文档部分【提供参考】:

默认情况下,Elastic 只允许本机访问,如果需要远程访问,可以修改 Elastic 安装目录的config/elasticsearch.yml文件,去掉network.host的注释,将它的值改成0.0.0.0,然后重新启动 Elastic。

network.host: 0.0.0.0

上面代码中,设成0.0.0.0让任何人都可以访问。线上服务不要这样设置,要设成具体的 IP。

二、基本概念

2.1 Node 与 Cluster

Elastic 本质上是一个分布式数据库,允许多台服务器协同工作,每台服务器可以运行多个 Elastic 实例。

单个 Elastic 实例称为一个节点(node)。一组节点构成一个集群(cluster)。

2.2 Index

Elastic 会索引所有字段,经过处理后写入一个反向索引(Inverted Index)。查找数据的时候,直接查找该索引。

所以,Elastic 数据管理的顶层单位就叫做 Index(索引)。它是单个数据库的同义词。每个 Index (即数据库)的名字必须是小写。

下面的命令可以查看当前节点的所有 Index。

$ curl -X GET 'http://localhost:9200/_cat/indices?v'

2.3 Document

Index 里面单条的记录称为 Document(文档)。许多条 Document 构成了一个 Index。

Document 使用 JSON 格式表示,下面是一个例子。

{
  "user": "张三",
  "title": "工程师",
  "desc": "数据库管理"
}

同一个 Index 里面的 Document,不要求有相同的结构(scheme),但是最好保持相同,这样有利于提高搜索效率。

2.4 Type

Document 可以分组,比如weather这个 Index 里面,可以按城市分组(北京和上海),也可以按气候分组(晴天和雨天)。这种分组就叫做 Type,它是虚拟的逻辑分组,用来过滤 Document。

不同的 Type 应该有相似的结构(schema),举例来说,id字段不能在这个组是字符串,在另一个组是数值。这是与关系型数据库的表的一个区别。性质完全不同的数据(比如products和logs)应该存成两个 Index,而不是一个 Index 里面的两个 Type(虽然可以做到)。

下面的命令可以列出每个 Index 所包含的 Type。

$ curl 'localhost:9200/_mapping?pretty=true'

根据规划,Elastic 6.x 版只允许每个 Index 包含一个 Type,7.x 版将会彻底移除 Type。

三、新建和删除 Index

新建 Index,可以直接向 Elastic 服务器发出 PUT 请求。下面的例子是新建一个名叫weather的 Index。

$ curl -X PUT 'localhost:9200/weather'

服务器返回一个 JSON 对象,里面的acknowledged字段表示操作成功。

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

然后,我们发出 DELETE 请求,删除这个 Index。

$ curl -X DELETE 'localhost:9200/weather'

四、中文分词设置

首先,安装中文分词插件。这里使用的是 ik,也可以考虑其他插件(比如 smartcn)。

$ ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.5.1/elasticsearch-analysis-ik-5.5.1.zip

上面代码安装的是5.5.1版的插件,与 Elastic 5.5.1 配合使用。

接着,重新启动 Elastic,就会自动加载这个新安装的插件。

然后,新建一个 Index,指定需要分词的字段。这一步根据数据结构而异,下面的命令只针对本文。基本上,凡是需要搜索的中文字段,都要单独设置一下。

$ curl -X PUT 'localhost:9200/accounts' -d '
{
  "mappings": {
    "person": {
      "properties": {
        "user": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_max_word"
        },
        "title": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_max_word"
        },
        "desc": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_max_word"
        }
      }
    }
  }
}'

上面代码中,首先新建一个名称为accounts的 Index,里面有一个名称为person的 Type。person有三个字段。

  • § user
  • § title
  • § desc

这三个字段都是中文,而且类型都是文本(text),所以需要指定中文分词器,不能使用默认的英文分词器。

Elastic 的分词器称为 analyzer。我们对每个字段指定分词器。

 
"user": {
  "type": "text",
  "analyzer": "ik_max_word",
  "search_analyzer": "ik_max_word"
}

上面代码中,analyzer是字段文本的分词器,search_analyzer是搜索词的分词器。ik_max_word分词器是插件ik提供的,可以对文本进行最大数量的分词。

五、数据操作

5.1 新增记录

向指定的 /Index/Type 发送 PUT 请求,就可以在 Index 里面新增一条记录。比如,向/accounts/person发送请求,就可以新增一条人员记录。

$ curl -X PUT 'localhost:9200/accounts/person/1' -d '
{
  "user": "张三",
  "title": "工程师",
  "desc": "数据库管理"
}' 

服务器返回的 JSON 对象,会给出 Index、Type、Id、Version 等信息。

{
  "_index":"accounts",
  "_type":"person",
  "_id":"1",
  "_version":1,
  "result":"created",
  "_shards":{"total":2,"successful":1,"failed":0},
  "created":true
}

如果你仔细看,会发现请求路径是/accounts/person/1,最后的1是该条记录的 Id。它不一定是数字,任意字符串(比如abc)都可以。

新增记录的时候,也可以不指定 Id,这时要改成 POST 请求。

$ curl -X POST 'localhost:9200/accounts/person' -d '
{
  "user": "李四",
  "title": "工程师",
  "desc": "系统管理"
}'

上面代码中,向/accounts/person发出一个 POST 请求,添加一个记录。这时,服务器返回的 JSON 对象里面,_id字段就是一个随机字符串。

{
  "_index":"accounts",
  "_type":"person",
  "_id":"AV3qGfrC6jMbsbXb6k1p",
  "_version":1,
  "result":"created",
  "_shards":{"total":2,"successful":1,"failed":0},
  "created":true
}

注意,如果没有先创建 Index(这个例子是accounts),直接执行上面的命令,Elastic 也不会报错,而是直接生成指定的 Index。所以,打字的时候要小心,不要写错 Index 的名称。

5.2 查看记录

向/Index/Type/Id发出 GET 请求,就可以查看这条记录。

$ curl 'localhost:9200/accounts/person/1?pretty=true'

上面代码请求查看/accounts/person/1这条记录,URL 的参数pretty=true表示以易读的格式返回。

返回的数据中,found字段表示查询成功,_source字段返回原始记录。

{
  "_index" : "accounts",
  "_type" : "person",
  "_id" : "1",
  "_version" : 1,
  "found" : true,
  "_source" : {
    "user" : "张三",
    "title" : "工程师",
    "desc" : "数据库管理"
  }
}

如果 Id 不正确,就查不到数据,found字段就是false。

$ curl 'localhost:9200/weather/beijing/abc?pretty=true'
{
  "_index" : "accounts",
  "_type" : "person",
  "_id" : "abc",
  "found" : false
}

5.3 删除记录

删除记录就是发出 DELETE 请求。

$ curl -X DELETE 'localhost:9200/accounts/person/1'

这里先不要删除这条记录,后面还要用到。

5.4 更新记录

更新记录就是使用 PUT 请求,重新发送一次数据。

$ curl -X PUT 'localhost:9200/accounts/person/1' -d '
{
    "user" : "张三",
    "title" : "工程师",
    "desc" : "数据库管理,软件开发"
}' 
 
{
  "_index":"accounts",
  "_type":"person",
  "_id":"1",
  "_version":2,
  "result":"updated",
  "_shards":{"total":2,"successful":1,"failed":0},
  "created":false
}

上面代码中,我们将原始数据从"数据库管理"改成"数据库管理,软件开发"。 返回结果里面,有几个字段发生了变化。

"_version" : 2,
"result" : "updated",
"created" : false

可以看到,记录的 Id 没变,但是版本(version)从1变成2,操作类型(result)从created变成updated,created字段变成false,因为这次不是新建记录。

六、数据查询

6.1 返回所有记录

使用 GET 方法,直接请求/Index/Type/_search,就会返回所有记录。

$ curl 'localhost:9200/accounts/person/_search'
{
  "took":2,
  "timed_out":false,
  "_shards":{"total":5,"successful":5,"failed":0},
  "hits":{
    "total":2,
    "max_score":1.0,
    "hits":[
      {
        "_index":"accounts",
        "_type":"person",
        "_id":"AV3qGfrC6jMbsbXb6k1p",
        "_score":1.0,
        "_source": {
          "user": "李四",
          "title": "工程师",
          "desc": "系统管理"
        }
      },
      {
        "_index":"accounts",
        "_type":"person",
        "_id":"1",
        "_score":1.0,
        "_source": {
          "user" : "张三",
          "title" : "工程师",
          "desc" : "数据库管理,软件开发"
        }
      }
    ]
  }
}

上面代码中,返回结果的 took字段表示该操作的耗时(单位为毫秒),timed_out字段表示是否超时,hits字段表示命中的记录,里面子字段的含义如下。

  • § total:返回记录数,本例是2条。
  • § max_score:最高的匹配程度,本例是1.0
  • § hits:返回的记录组成的数组。

返回的记录中,每条记录都有一个_score字段,表示匹配的程序,默认是按照这个字段降序排列。

6.2 全文搜索

Elastic 的查询非常特别,使用自己的查询语法,要求 GET 请求带有数据体。

 
$ curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query" : { "match" : { "desc" : "软件" }}
}'

上面代码使用 Match查询,指定的匹配条件是desc字段里面包含"软件"这个词。返回结果如下。

 
{
  "took":3,
  "timed_out":false,
  "_shards":{"total":5,"successful":5,"failed":0},
  "hits":{
    "total":1,
    "max_score":0.28582606,
    "hits":[
      {
        "_index":"accounts",
        "_type":"person",
        "_id":"1",
        "_score":0.28582606,
        "_source": {
          "user" : "张三",
          "title" : "工程师",
          "desc" : "数据库管理,软件开发"
        }
      }
    ]
  }
}

Elastic 默认一次返回10条结果,可以通过size字段改变这个设置。

 
$ curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query" : { "match" : { "desc" : "管理" }},
  "size": 1
}'

上面代码指定,每次只返回一条结果。

还可以通过from字段,指定位移。

 
$ curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query" : { "match" : { "desc" : "管理" }},
  "from": 1,
  "size": 1
}'

上面代码指定,从位置1开始(默认是从位置0开始),只返回一条结果。

6.3 逻辑运算

如果有多个搜索关键字, Elastic 认为它们是or关系。

 
$ curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query" : { "match" : { "desc" : "软件 系统" }}
}'

上面代码搜索的是软件 or 系统。

如果要执行多个关键词的and搜索,必须使用布尔查询

 
$ curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query": {
    "bool": {
      "must": [
        { "match": { "desc": "软件" } },
        { "match": { "desc": "系统" } }
      ]
    }
  }
}'