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": "系統" } }
      ]
    }
  }
}'
相關文章
相關標籤/搜索