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

 

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

 

一、         总体简介:php

模式:单机css

平台:Linux - centos - 7html

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

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

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

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

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

二、         软件环境安装:github

(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 &

三、         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的相关命令写入到启动脚本简化操做。

四、         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'

 

五、          附录图片

filebeat发送字段:

 

 

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

 

默认状况下,Elastic 只容许本机访问,若是须要远程访问,能够修改 Elastic 安装目录的config/elasticsearch.yml文件,去掉network.host的注释,将它的值改为0.0.0.0,而后从新启动 Elastic。

.:0.0.0.0networkhost

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

2、基本概念

2.1 Node 与 Cluster

Elastic 本质上是一个分布式数据库,容许多台服务器协同工做,每台服务器能够运行多个 Elastic 实例。

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

2.2 Index

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

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

下面的命令能够查看当前节点的全部 Index。

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

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。

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

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

3、新建和删除 Index

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

-'localhost:9200/weather'$ curlX PUT

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

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

而后,咱们发出 DELETE 请求,删除这个 Index。

-'localhost:9200/weather'$ curlX DELETE

4、中文分词设置

首先,安装中文分词插件。这里使用的是 ik,也能够考虑其余插件(好比 smartcn)。

.//-://.//--///.5.1/---5.5.1.$binelasticsearchplugin install httpsgithubcommedclelasticsearchanalysisikreleasesdownloadv5elasticsearchanalysisikzip

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

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

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

-'localhost:9200/accounts'-'$ curlX PUTd
{
  "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、数据操做

5.1 新增记录

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

-'localhost:9200/accounts/person/1'-'$ curlX PUTd
{
  "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 请求。

-'localhost:9200/accounts/person'-'$ curlX POSTd
{
  "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 请求,就能够查看这条记录。

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

上面代码请求查看/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。

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

5.3 删除记录

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

-'localhost:9200/accounts/person/1'$ curlX DELETE

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

5.4 更新记录

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

-'localhost:9200/accounts/person/1'-'$ curlX PUTd
{
    "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、数据查询

6.1 返回全部记录

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

'localhost:9200/accounts/person/_search'$ curl
{
"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 请求带有数据体。

 
'localhost:9200/accounts/person/_search'-'$ curl 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字段改变这个设置。

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

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

还能够经过from字段,指定位移。

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

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

6.3 逻辑运算

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

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

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

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

 
'localhost:9200/accounts/person/_search'-'$ curl d
{
  "query": {
    "bool": {
      "must": [
        { "match": { "desc": "软件" } },
        { "match": { "desc": "系统" } }
      ]
    }
  }
}'
相关文章
相关标签/搜索