input 부분

input {
    exec {
        command  => "/usr/bin/python3 /home/kimjh/Desktop/logstashQuery/01/jsonRead.py"
        interval => 120
    }
}

python 코드 부분

 

json 파일 

=> logstash 는 ndjson 형태의 파일을 read 한다. 하지만 다음은 일반적인 json 파일이다. 이를 읽기 위해 위와 같은 파이썬 코드를 짰고 그것을 logstash의 input에 넣었다.

$ cat test_sample.json
{
        "2010": {"name2": "kim1"},
        "2011": {"name2": "kim2"},
        "2012": {"name2": "kim3"},
        "2013": {"name2": "kim4"},
        "2014": {"name2": "kim5"}
}

filter 부분

filter {
    ruby {
        code => '
                require "elasticsearch"
                require "json"
                require "yaml"

                esClient = Elasticsearch::Client.new
                actionArray = Array.new

                jsonDatas = event.get("message")
                if ! jsonDatas.nil?
                    jsonArry  = jsonDatas.split("\n")
                    jsonArry.each_with_index do |n, c|
                        #puts n.class
                        strHash = YAML.load(n)
                        hashData = {
                                    "index" => {
                                        "_index"  => "sleep4",
                                        "_id"     => c,
                                        "data" => {}
                                        }
                                    }

                        hashData["index"]["data"].merge!strHash
                        actionArray.push(hashData)
                    end
                end
                if ! actionArray.empty?
                    actionArray.each do |n|
                        p n
                    end
                    esClient.bulk body: actionArray
                end
                '
    }

    mutate {
        remove_field => ["@timestamp", "host", "command", "@version"]
    }
}

 

1) split : 문자열 분리 

=> 특정 char를 기준으로 문자열을 자르게 된다.

 

2) each_with_index : python 과 비교하자면 enumerate 와 동일하게 작동

 

3) empty?

=> 데이터가 비어있는지 확인 비어있으면 true 반환 아니면 false 반환

 

4) push

=> array에 데이터 삽입

'언어 > Ruby' 카테고리의 다른 글

ruby json 파일 읽기  (0) 2020.07.02
ruby + elasticsearch indices/ health  (0) 2020.07.02
ruby elasticsearch client  (0) 2020.05.26
cea(ver3)  (0) 2016.02.27
class  (0) 2016.02.27

begin

 # 예외가 발생할 가능성이 있는 문구

rescue => e

 # 적절한 예외 처리

else

 # 예외 발생없이 정상 처리

ensure

 # 예외 발생과 상관없이 처리

end

 

======================================================

json 파일을 읽어서 elasticsearch client를 셋업해보자

'언어 > Ruby' 카테고리의 다른 글

logstash ruby filter elasticsearch bulk insert  (0) 2020.07.22
ruby + elasticsearch indices/ health  (0) 2020.07.02
ruby elasticsearch client  (0) 2020.05.26
cea(ver3)  (0) 2016.02.27
class  (0) 2016.02.27

1. elasticsearch cluster 의 health 체크

: esClient.cluster.health => 응답으로 받은 데이터는 hash 형태의 리턴값

 

{"cluster_name"=>"elasticsearch", "status"=>"yellow", "timed_out"=>false, "number_of_nodes"=>1, "number_of_data_nodes"=>1, "active_primary_shards"=>15, "active_shards"=>15, "relocating_shards"=>0, "initializing_shards"=>0, "unassigned_shards"=>15, "delayed_unassigned_shards"=>0, "number_of_pending_tasks"=>0, "number_of_in_flight_fetch"=>0, "task_max_waiting_in_queue_millis"=>0, "active_shards_percent_as_number"=>50.0}

 

2. 전체 인덱스 확인

: esClient.cat.indices => 응답으로 받은 데이터는 string 형태의 리턴값

: shell 로 코드를 구성한다면 다음과 같다.

#!/bin/bash

curl -XGET localhost:9200/_cat/indices?pretty

 

3. document indexing

: shell 로 코드를 구성한다면 다음과 같다.

#!/bin/bash

curl -X POST "localhost:9200/index_data" -H "Content-Type: application/json" -d'

{

  "name": "KimJunHyeon"

}' 

 

4. delete_by_query

: 인덱스의 껍데기 (mapping)을 유지한 상태에서 모든 document를 지워야할 경우가 생긴다. 그럴경우 

delete_by_query 문을 사용한다.

 

: shell 로 코드를 구성한다면 다음과 같다.

#!/bin/bash

curl -X POST "localhost:9200/index_data/_delete_by_query" -H "Content-Type: application/json" -d'
{
  "query": {
     "match_all": {}
  }
}'

 

'언어 > Ruby' 카테고리의 다른 글

logstash ruby filter elasticsearch bulk insert  (0) 2020.07.22
ruby json 파일 읽기  (0) 2020.07.02
ruby elasticsearch client  (0) 2020.05.26
cea(ver3)  (0) 2016.02.27
class  (0) 2016.02.27

require 'elasticsearch/transport'
require 'elasticsearch'

client = Elasticsearch::Client.new hosts: [
    { host: '',
      port: 9200,
      user: "",
      password: ""
    }
]

#client.index  index: 'myindex', type: 'mytype', id: 1, body: { title: 'Test' }
response = client.search index: 'myindex', body: { query: { match: { title: 'test' } } }
puts response["hits"]["hits"][0]["_source"]
require import
   

'언어 > Ruby' 카테고리의 다른 글

ruby json 파일 읽기  (0) 2020.07.02
ruby + elasticsearch indices/ health  (0) 2020.07.02
cea(ver3)  (0) 2016.02.27
class  (0) 2016.02.27
루비(ruby)상속 -> 상속 -> 상속  (0) 2016.02.26

cea(ver3)

언어/Ruby2016. 2. 27. 12:17
# =================== Echo Function ==========================
class Echo
def Function__Echo__PlainText(plainText)
print("Plaintext is [ #{plainText} ] \n")
end

def Function__Echo__RandomKey(key)
print("RandomKey is [ #{key} ] \n")
end

def Function__Echo__Field(flist)
print("Field list is #{flist} \n")
end

def Function__Echo__CipherText(cipherText)
print("Ciphertext is #{cipherText} \n")
end

def Function__Echo__Field_LEN(fieldlen)
print("Field Length is #{fieldlen} \n")
end

def Function__Echo__DecryptText(decrypt)
print("DecryptText is #{decrypt} \n")
end
end
# =================== Main Function ==========================
class CEA < Echo
attr_accessor :STRING__plaintext
attr_accessor :STRING__ciphertext
attr_accessor :INT__random_cea_key
attr_accessor :STRING__decrypt_plaintext
attr_accessor :INT__plaintext_LEN
attr_accessor :FieldList
attr_accessor :INT__FieldList_LEN
def initialize
@STRING__plaintext = ""
@STRING__ciphertext = ""
@INT__random_cea_key = 0
@STRING__decrypt_plaintext = ""
@FieldList = []
@INT__FieldList_LEN = 0
end
#[Func 1]--------------------------------------------------------
def Function__FieldList_SETTING
(97..122).each do |encoding| #a, b, c, d, ..., z
@FieldList.push(encoding.chr)
end
(65..90).each do |encoding| #A, B, C, D, ..., Z
@FieldList.push(encoding.chr)
end
(''..'').each do |hangul|
@FieldList.push(hangul)
end
@FieldList.push(" ")
@FieldList = @FieldList.shuffle
@INT__FieldList_LEN = @FieldList.length
end
#[Func 2]--------------------------------------------------------
def Function__Random_Secret_Key
@INT__random_cea_key = Random.new
@INT__random_cea_key = rand(1...@INT__FieldList_LEN) # 1, 2, 3, 4, ...,25
end
#[Func 3]--------------------------------------------------------
def Function__Encrypt
@STRING__plaintext.each_char do |plainT_CHAR|
if (@FieldList.include?(plainT_CHAR))
position = @FieldList.index(plainT_CHAR)
position = (position + @INT__random_cea_key)%@INT__FieldList_LEN
@STRING__ciphertext = @STRING__ciphertext + @FieldList[position]
else
@STRING__ciphertext = @STRING__ciphertext + plainT_CHAR
end
end
end
#[Func 3]--------------------------------------------------------
def Function__Decrypt
@STRING__ciphertext.each_char do |ciphterT_CHAR|
if (@FieldList.include?(ciphterT_CHAR))
position = @FieldList.index(ciphterT_CHAR)
position = (position - @INT__random_cea_key)%@INT__FieldList_LEN
@STRING__decrypt_plaintext = @STRING__decrypt_plaintext + @FieldList[position]
else
@STRING__decrypt_plaintext = @STRING__decrypt_plaintext + ciphterT_CHAR
end
end
end
end

#===================== << MAIN >> ===========================
def main
cea = CEA.new
cea.Function__FieldList_SETTING
cea.Function__Echo__Field(cea.FieldList)
cea.Function__Echo__Field_LEN(cea.INT__FieldList_LEN)
cea.STRING__plaintext = gets.chomp.to_s
cea.Function__Random_Secret_Key
cea.Function__Echo__PlainText(cea.STRING__plaintext)
cea.Function__Echo__RandomKey(cea.INT__random_cea_key)
cea.Function__Encrypt
cea.Function__Echo__CipherText(cea.STRING__ciphertext)
cea.Function__Decrypt
cea.Function__Echo__DecryptText(cea.STRING__decrypt_plaintext)
end
main


'언어 > Ruby' 카테고리의 다른 글

ruby + elasticsearch indices/ health  (0) 2020.07.02
ruby elasticsearch client  (0) 2020.05.26
class  (0) 2016.02.27
루비(ruby)상속 -> 상속 -> 상속  (0) 2016.02.26
시저 (ver2) 확실히 루비는 파이썬과 형제언어다  (0) 2016.02.20

class

언어/Ruby2016. 2. 27. 10:30


class STU3
def hello
puts 'Hello, Parent'
end
end

class Child < STU3
def hello
super # <---------------------------------- STU3의 hello 호출한다.
puts 'Hello, Child'
end
end

st = Child.new
st.hello

Hello, Parent
Hello, Child

Process finished with exit code 0

'언어 > Ruby' 카테고리의 다른 글

ruby elasticsearch client  (0) 2020.05.26
cea(ver3)  (0) 2016.02.27
루비(ruby)상속 -> 상속 -> 상속  (0) 2016.02.26
시저 (ver2) 확실히 루비는 파이썬과 형제언어다  (0) 2016.02.20
class 상속  (0) 2016.02.13

class STU1
attr_accessor :value1 #인스턴스 변수에 접근하기 위한 메소드
attr_accessor :value2
def initialize(value1, value2)
@value1 = value1
@value2 = value2
end
def multiplication_function
print"#{@value1} x #{@value2} = #{@value1 * @value2} \n"
end
end

class STU2 < STU1
attr_accessor :value1 #인스턴스 변수에 접근하기 위한 메소드
attr_accessor :value2
def initialize(value1, value2)
@value1 = value1
@value2 = value2
end
def summaiton_function
print"#{@value1} + #{@value2} = #{@value1 + @value2} \n"
end
end

class STU3 < STU2
attr_accessor :value1 #인스턴스 변수에 접근하기 위한 메소드
attr_accessor :value2
def initialize(value1, value2)
@value1 = value1
@value2 = value2
end
def submation_function
print"#{@value1} - #{@value2} = #{@value1 - @value2} \n"
end
end
=begin
st = STU2.new(1,2)
st.summaiton_function
=end
st = STU3.new(4,5)
st.summaiton_function
st.submation_function
st.multiplication_functio


'언어 > Ruby' 카테고리의 다른 글

cea(ver3)  (0) 2016.02.27
class  (0) 2016.02.27
시저 (ver2) 확실히 루비는 파이썬과 형제언어다  (0) 2016.02.20
class 상속  (0) 2016.02.13
class def  (0) 2016.02.13

class CEA
# [1] ----------------------------------------------
def initialize
@plainText_String = ''
@plainText_Decrypt_String = ''
@plainText_length_int = 0
@cea_random_key = 0
@cipherText_String = ''
@field_LIST = Array.new # ****** Array.new
@field_String = ''
@fidld_length_int = 0
end
def field_setting
for i in (65..90) # range[65, 66, 67, 68, ..., 90]
@field_LIST.push(i.chr) # ****** .push(i.chr)
end

for i in (97..122) # range[97, 98, 99, 100, ..., 122]
@field_LIST.push(i.chr) # ****** .push(i.chr)
end

@field_LIST = @field_LIST.shuffle # python shuffle
print("#{@field_LIST} \n")
@field_String =@field_LIST.join('')
@fidld_length_int = @field_String.length
print("#{@field_String} \n") # python join vs
print("[ECHO @fidld_length_int]-> #{@fidld_length_int} \n")
end
# --------------------------------------------------
# [2] ----------------------------------------------
def plaintext_Write_function
print("plaintext is ")
@plainText_String = gets.chomp.to_s
@plainText_length_int = @plainText_String.length
print("[ECHO @plainText_String]-> #{@plainText_String} \n")
print("[ECHO @plainText_length_int]-> #{@plainText_length_int} \n")
end
# --------------------------------------------------
# [3] ----------------------------------------------
def ceasar_random_key_function
@cea_random_key = rand(1...25)
print("[ECHO @cea_random_key]-> #{@cea_random_key} \n")
end
# --------------------------------------------------
# [4] ----------------------------------------------
def encrypt_ceasar_function
for i in (0...@plainText_String.length)
#print("#{@field_LIST.index(@plainText_String[i])} \n") # python find
if(@field_String.include?(@plainText_String[i]))
number_int = ( @field_LIST.index(@plainText_String[i]) + @cea_random_key )%@fidld_length_int
@cipherText_String +=@field_String[number_int]
else
@cipherText_String +=@plainText_String[i]
end
end
print("[ECHO @cipherText_String]-> #{@cipherText_String} \n")
end
# --------------------------------------------------
# [5] ----------------------------------------------
def decrypt_ceasar_function
for i in (0...@plainText_String.length)
#print("#{@field_LIST.index(@plainText_String[i])} \n") # python find
if(@field_String.include?(@cipherText_String[i]))
number_int = ( @field_LIST.index(@cipherText_String[i]) - @cea_random_key )%@fidld_length_int
@plainText_Decrypt_String +=@field_String[number_int]
else
@plainText_Decrypt_String +=@cipherText_String[i]
end
end
print("[ECHO @plainText_Decrypt_String]-> #{@plainText_Decrypt_String} \n")
end
end
#---------------------[ main_function ]---------------------
ceasar = CEA.new
ceasar.field_setting
ceasar.plaintext_Write_function
ceasar.ceasar_random_key_function
ceasar.encrypt_ceasar_function
ceasar.decrypt_ceasar_function
#-----------------------------------------------------------


'언어 > Ruby' 카테고리의 다른 글

class  (0) 2016.02.27
루비(ruby)상속 -> 상속 -> 상속  (0) 2016.02.26
class 상속  (0) 2016.02.13
class def  (0) 2016.02.13
ruby [전역변수]  (0) 2016.02.13

class 상속

언어/Ruby2016. 2. 13. 11:12
#coding: utf-8
#super class-----------------------------------------------------------------
class CALCULATION #클래스명은 반드시 대문자
def initialize
@value_left = 0 #인스턴스 변수 python에서 self 같은 것 같다
@value_right = 0 #인스턴스 변수 python에서 self 같은 것 같다
end
def insert()
print("@value_left input >>> ")
@value_left = gets.chomp.to_i #gets.chomp.to_i 이거 중요하다 반드시 머리에 숙지해라

print("@value_right input >>> ")
@value_right = gets.chomp.to_i
end
def summation_function()
print("#{@value_left} + #{@value_right} = #{@value_left + @value_right}")
end
end

#sub class-----------------------------------------------------------------
class Child < CALCULATION
def initialize
@value_left = 0 #인스턴스 변수 python에서 self 같은 것 같다
@value_right = 0 #인스턴스 변수 python에서 self 같은 것 같다
end
def insert_1()
print("@value_left input >>> ")
@value_left = gets.chomp.to_i #gets.chomp.to_i 이거 중요하다 반드시 머리에 숙지해라

print("@value_right input >>> ")
@value_right = gets.chomp.to_i
end
def subtraction(a, b)
print("#{a} - #{b} = #{a-b}")
end
end
#-----------main---------------
stu = Child.new
stu.insert_1()
stu.summation_function()


'언어 > Ruby' 카테고리의 다른 글

루비(ruby)상속 -> 상속 -> 상속  (0) 2016.02.26
시저 (ver2) 확실히 루비는 파이썬과 형제언어다  (0) 2016.02.20
class def  (0) 2016.02.13
ruby [전역변수]  (0) 2016.02.13
ruby [계산기]  (0) 2016.02.12

class def

언어/Ruby2016. 2. 13. 10:58

class class_name(반드시 대문자)

end


#coding: utf-8
class CALCULATION #클래스명은 반드시 대문자
def initialize
@value_left = 0 #인스턴스 변수 python에서 self 같은 것 같다
@value_right = 0 #인스턴스 변수 python에서 self 같은 것 같다
end
def insert()
print("@value_left input >>> ")
@value_left = gets.chomp.to_i #gets.chomp.to_i 이거 중요하다 반드시 머리에 숙지해라

print("@value_right input >>> ")
@value_right = gets.chomp.to_i
end
def summation_function()
print("#{@value_left} + #{@value_right} = #{@value_left + @value_right}")
end
end

#-----------main---------------
stu = CALCULATION.new
stu.insert()
stu.summation_function()

python

class CAL:
def __init__(self):
self.value1 = 0
self.value2 = 0


'언어 > Ruby' 카테고리의 다른 글

시저 (ver2) 확실히 루비는 파이썬과 형제언어다  (0) 2016.02.20
class 상속  (0) 2016.02.13
ruby [전역변수]  (0) 2016.02.13
ruby [계산기]  (0) 2016.02.12
ruby [ 구구단 ]  (0) 2016.02.11