<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>data-traveler</title>
        <link>https://velog.io/</link>
        <description> Go with the flow</description>
        <lastBuildDate>Sun, 17 Apr 2022 08:49:36 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>data-traveler</title>
            <url>https://velog.velcdn.com/images/data-traveler/profile/2aa95898-6afc-433f-8ae1-5e4262a06921/image.jpeg</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. data-traveler. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/data-traveler" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[2222]]></title>
            <link>https://velog.io/@data-traveler/2222</link>
            <guid>https://velog.io/@data-traveler/2222</guid>
            <pubDate>Sun, 17 Apr 2022 08:49:36 GMT</pubDate>
            <description><![CDATA[<h3 id="배치-추가">배치 추가</h3>
<p>&quot;keyword_matching_init.py&quot;</p>
<pre><code class="language-python">if __name__ == &quot;__main__&quot;:
    data_path = &quot;/home/ubuntu/src/script/curation/data&quot;
    ...
    ...
    file_list = os.listdir(data_path)</code></pre>
<p>위 코드를 통해서 배치 작업을 진행함 &quot;data_path&quot; 아래 위치한 파일 명을 읽어서 이를 바탕으로 배치 작업을 진행</p>
<p>— batch 작업 중 오류가 발생할 경우 보통 data_path에 csv, xlsx 확장자가 아닌 파일이 있을 경우임 → 숨겨진 파일이 있을 수도 있으므로 직접 cmd 라인에서 확인 할 필요가 있음.</p>
<p><a href="https://www.notion.so/5847b60e42994206986acc1fb53d8744">주관식 자동채점 적용 현황 리스트</a></p>
<ul>
<li>과목 수 : 240,  문항 수 : 2820</li>
<li>정확률 : 99.03 % ( 총 채점 수 : 34161 / 올바르게 채점한 수 : 33832 )</li>
<li>2021-07-14 기준</li>
</ul>
<p><a href="http://imply.hunet.co.kr">imply.hunet.co.kr</a> 에 들어가서 SQL 접속 후</p>
<p>subjective_question_verification</p>
<p>테이블을 통해 확인 할수 있음.</p>
<pre><code class="language-sql">-- 올바르게 채점한 수
select count(*) from &quot;subjective_question_verification&quot;
where &quot;__time&quot; &gt;= &#39;2021-07-14&#39;
and correct_answer_rate &lt; 10
and correct_answer_rate &gt; 90

-- 총 채점 수
select count(*) from &quot;subjective_question_verification&quot;
where &quot;__time&quot; &gt;= &#39;2021-07-14&#39;
</code></pre>
<ul>
<li><p>주의사항</p>
<p>  초기 subjective_question_verification 테이블에 들어가던 값들에 대한 기준값이 바뀌었기 때문에 날짜 조건을 걸어서 기존에 책정해 둔것에 값을 더해가는 것이 정확함.</p>
<h2 id="3-gpt-3-pricing">3. GPT-3 Pricing</h2>
</li>
</ul>
<p>처음 GPT-3를 신청하면 Trial(무료 체험 이용 기간) 상태가 되고, 3개월간 30만 토큰을 사용할 수 있게 해 줍니다. 3개월이 지나거나, 그 이전에 30만 토큰을 다 쓴다면 아래와 같은 가격정책에 따라 GPT-3 모델을 사용할 수 있습니다.</p>
<p><img src="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0cdbe4d3-ddfd-4160-9cdc-9dc5dd16a40e/Untitled.png" alt="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0cdbe4d3-ddfd-4160-9cdc-9dc5dd16a40e/Untitled.png"></p>
<p>1 Token = 영어 4글자 정도로 생각하면 된다고 합니다. 짧은 단어 한개 정도를 의미한다고 보면 편할 것 같습니다.</p>
<h2 id="4-gpt-3-turorial">4. GPT-3 Turorial</h2>
<p>이제 기본적으로 GPT-3를 사용할 준비는 모두 마친 상태입니다. 그럼 파이썬에서 GPT-3를 사용하기 위해 라이브러리를 설치하고 사용하는 방법을 알아보도록 하겠습니다.</p>
<p>우선 가상환경에 openai 라이브러리를 설치합니다.</p>
<pre><code class="language-bash">$ conda create --n gpt python=3.7
$ conda activate gpt
(gpt) $ pip install openai</code></pre>
<p>설치까지 완료되었다면 간단한 코드를 통해 바로 테스트를 해볼 수 있습니다.</p>
<pre><code class="language-python">import openai

openapi.api_key = &quot;SECRET_API_KEY&quot;

prompt = &quot;This is a test&quot;

response = openai.Completion.create(engine=&quot;davinci&quot;, prompt=prompt, max_tokens=10)

print(response.choices[0].text)

------------------------------------------------------------------------------------
&#39; of whether the programming works correctly.\n\nHere&#39;</code></pre>
<h2 id="5-예제를-통해-학습시키기">5. 예제를 통해 학습시키기</h2>
<p>GPT-3는 few-shot learning을 통해 몇 가지 예제를 보여주면 성능이 더욱 좋아지는 모델입니다. 보다 효율적으로 활용하기 위해 GPT class와 Example class를 아래와 같이 생성해 줍니다.</p>
<p>(출처 : <a href="https://github.com/shreyashankar/gpt3-sandbox">https://github.com/shreyashankar/gpt3-sandbox</a>)</p>
<pre><code class="language-python">&quot;&quot;&quot;Creates the Example and GPT classes for a user to interface with the OpenAI
API.&quot;&quot;&quot;

import openai
import uuid

def set_openai_key(key):
    &quot;&quot;&quot;Sets OpenAI key.&quot;&quot;&quot;
    openai.api_key = key

class Example:
    &quot;&quot;&quot;Stores an input, output pair and formats it to prime the model.&quot;&quot;&quot;
    def __init__(self, inp, out):
        self.input = inp
        self.output = out
        self.id = uuid.uuid4().hex

    def get_input(self):
        &quot;&quot;&quot;Returns the input of the example.&quot;&quot;&quot;
        return self.input

    def get_output(self):
        &quot;&quot;&quot;Returns the intended output of the example.&quot;&quot;&quot;
        return self.output

    def get_id(self):
        &quot;&quot;&quot;Returns the unique ID of the example.&quot;&quot;&quot;
        return self.id

    def as_dict(self):
        return {
            &quot;input&quot;: self.get_input(),
            &quot;output&quot;: self.get_output(),
            &quot;id&quot;: self.get_id(),
        }

class GPT:
    &quot;&quot;&quot;The main class for a user to interface with the OpenAI API.

    A user can add examples and set parameters of the API request.
    &quot;&quot;&quot;
    def __init__(self,
                 engine=&#39;davinci&#39;,
                 temperature=0.5,
                 max_tokens=100,
                 input_prefix=&quot;input: &quot;,
                 input_suffix=&quot;\n&quot;,
                 output_prefix=&quot;output: &quot;,
                 output_suffix=&quot;\n\n&quot;,
                 append_output_prefix_to_query=False):
        self.examples = {}
        self.engine = engine
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.input_prefix = input_prefix
        self.input_suffix = input_suffix
        self.output_prefix = output_prefix
        self.output_suffix = output_suffix
        self.append_output_prefix_to_query = append_output_prefix_to_query
        self.stop = (output_suffix + input_prefix).strip()

    def add_example(self, ex):
        &quot;&quot;&quot;Adds an example to the object.

        Example must be an instance of the Example class.
        &quot;&quot;&quot;
        assert isinstance(ex, Example), &quot;Please create an Example object.&quot;
        self.examples[ex.get_id()] = ex

    def delete_example(self, id):
        &quot;&quot;&quot;Delete example with the specific id.&quot;&quot;&quot;
        if id in self.examples:
            del self.examples[id]

    def get_example(self, id):
        &quot;&quot;&quot;Get a single example.&quot;&quot;&quot;
        return self.examples.get(id, None)

    def get_all_examples(self):
        &quot;&quot;&quot;Returns all examples as a list of dicts.&quot;&quot;&quot;
        return {k: v.as_dict() for k, v in self.examples.items()}

    def get_prime_text(self):
        &quot;&quot;&quot;Formats all examples to prime the model.&quot;&quot;&quot;
        return &quot;&quot;.join(
            [self.format_example(ex) for ex in self.examples.values()])

    def get_engine(self):
        &quot;&quot;&quot;Returns the engine specified for the API.&quot;&quot;&quot;
        return self.engine

    def get_temperature(self):
        &quot;&quot;&quot;Returns the temperature specified for the API.&quot;&quot;&quot;
        return self.temperature

    def get_max_tokens(self):
        &quot;&quot;&quot;Returns the max tokens specified for the API.&quot;&quot;&quot;
        return self.max_tokens

    def craft_query(self, prompt):
        &quot;&quot;&quot;Creates the query for the API request.&quot;&quot;&quot;
        q = self.get_prime_text(
        ) + self.input_prefix + prompt + self.input_suffix
        if self.append_output_prefix_to_query:
            q = q + self.output_prefix

        return q

    def submit_request(self, prompt):
        &quot;&quot;&quot;Calls the OpenAI API with the specified parameters.&quot;&quot;&quot;
        response = openai.Completion.create(engine=self.get_engine(),
                                            prompt=self.craft_query(prompt),
                                            max_tokens=self.get_max_tokens(),
                                            temperature=self.get_temperature(),
                                            top_p=1,
                                            n=1,
                                            stream=False,
                                            stop=self.stop)
        return response

    def get_top_reply(self, prompt):
        &quot;&quot;&quot;Obtains the best result as returned by the API.&quot;&quot;&quot;
        response = self.submit_request(prompt)
        return response[&#39;choices&#39;][0][&#39;text&#39;]

    def format_example(self, ex):
        &quot;&quot;&quot;Formats the input, output pair.&quot;&quot;&quot;
        return self.input_prefix + ex.get_input(
        ) + self.input_suffix + self.output_prefix + ex.get_output(
        ) + self.output_suffix</code></pre>
<p><a href="http://gpt.py">gpt.py</a> 파일을 만들었다면 이제 예제를 통해 쿼리를 생성하는 gpt-3 모델을 학습해 줍니다.</p>
<pre><code class="language-python">gpt = GPT(engine=&quot;davinci&quot;,
                    temperature=0.5,
                    max_tokens=100)

gpt.add_example(Example(&#39;Fetch unique values of DEPARTMENT from Worker table.&#39;,
                        &#39;Select distinct DEPARTMENT from Worker;&#39;))

gpt.add_example(Example(&#39;Print the first three characters of FIRST_NAME from Worker table.&#39;,
                        &#39;Select substring(FIRST_NAME,1,3) from Worker;&#39;))

gpt.add_example(Example(&#39;Find the position of the alphabet (&quot;a&quot;) in the first name column &quot;Amitabh&quot; from Worker table.&#39;,
                        &#39;Select INSTR(FIRST_NAME, BINARY&quot;a&quot;) from Worker where FIRST_NAME = &quot;Amitabh&quot;;&#39;))

gpt.add_example(Example(&#39;Print the FIRST_NAME from Worker table after replacing &quot;a&quot; with &quot;A&quot;.&#39;,
                        &#39;Select CONCAT(FIRST_NAME, &quot; &quot;, LAST_NAME) AS &quot;COMPLETE_NAME&quot; from Worker;&#39;))

gpt.add_example(Example(&#39;Display the second highest salary from the Worker table.&#39;,
                        &#39;Select max(Salary) from Worker where Salary not in (Select max(Salary) from Worker);&#39;))

gpt.add_example(Example(&#39;Display the highest salary from the Worker table.&#39;,
                        &#39;Select max(Salary) from Worker;&#39;))

gpt.add_example(Example(&#39;Fetch the count of employees working in the department Admin.&#39;,
                        &#39;SELECT COUNT(*) FROM worker WHERE DEPARTMENT = &quot;Admin&quot;;&#39;))

gpt.add_example(Example(&#39;Get all details of the workers whose SALARY lies between 100000 and 500000.&#39;,
                        &#39;Select * from Worker where SALARY between 100000 and 500000;&#39;))

gpt.add_example(Example(&#39;Get Salary details of the Workers&#39;,
                        &#39;Select Salary from Worker&#39;))</code></pre>
<p>이렇게 몇 가지 질의 - 쿼리 예제를 통해 GPT-3를 학습시킨다음 학습되지 않은 질의를 모델에 날리게되면, 아래와 같이 쿼리를 생성해 줍니다.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[test]]></title>
            <link>https://velog.io/@data-traveler/111</link>
            <guid>https://velog.io/@data-traveler/111</guid>
            <pubDate>Sun, 17 Apr 2022 08:48:26 GMT</pubDate>
            <description><![CDATA[<h2 id="test-environment-setting">test environment setting</h2>
<p>테스트를 위한 환경 세팅은 아래와 같습니다.</p>
<pre><code class="language-bash">pip install flask_restplus
pip install Werkzeug==0.16.1
pip install celery

# 버전이 낮은 버전이면 upgrade
pip install celery --upgrade

# python 안에서 redis 접속을 위하여 설치
pip install -y reids

celery --app celery_worker.celery worker --loglevel=info --pool=gevent --concurrency=10
celery worker -A celery_worker.celery --pool=gevent --concurrency=10

# pycurl 설치 시
yum install libcurl-devel
yum install gcc
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Kafka란 무엇인가]]></title>
            <link>https://velog.io/@data-traveler/Kafka%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80</link>
            <guid>https://velog.io/@data-traveler/Kafka%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80</guid>
            <pubDate>Sun, 17 Apr 2022 06:10:21 GMT</pubDate>
            <description><![CDATA[<h2 id="1-kafka-란-무엇인가">1) Kafka 란 무엇인가</h2>
<p>카프카는 <strong>Publish-Subscribe 모델을 구현한 분산 메시징 시스템</strong>이다.</p>
<p><strong>데이터 파이프라인(Data Pipeline)을 구축</strong>할 때
가장 많이 고려되는 시스템 중 하나가 &#39;카프카(Kafka)&#39; 일 것이다.</p>
<p><img src="https://velog.velcdn.com/images/data-traveler/post/e4d5877d-592c-4115-b975-8b621fd65201/image.png" alt=""></p>
<h2 id="2-kafka-탄생-배경">2) Kafka 탄생 배경</h2>
<p>LinkedIn에서 개발된 분산 메시징 시스템으로 2011년에 오픈소스로 공개되었다.</p>
<p><strong>[기존 링크드인 시스템의 가진 문제점]</strong></p>
<p>하나의 서비스가 너무 많은 시스템과 연결된다
그로 인해 유지 관리 부담은 더욱 더 늘어나게 되었고, 이로 인해 기능 개발 자체가 지연되었다</p>
<p>첫째 : 실시간 트랜잭션 처리와 비동기 처리가 동시에 이뤄지지만 통합된 전송 영역이 없으니 복잡도가 증가할 수밖에 없다.
둘째 :  통합 데이터 분석을 위해 서로 다른 데이터 시스템을 연결해야할 경우, 데이터의 포맷이나 처리하는 방법이 다르다면 통합하기가 어렵다. 또한 두 시스템 간의 데이터가 서로 달라져 신뢰도마저 낮아질 수 있다.</p>
<p><strong>[과거]</strong></p>
<p>과거에는 많은 서비스에서 생성되는 모든 이벤트의 부하를 견딜만한 버스 시스템이 없었다.
이전 세대에서는 회사 전체의 데이터가 파편화되어 총합적인 데이터 분석이 어려웠다.</p>
<p><strong>[현재]</strong></p>
<p><strong>클라우드 시대가 본격적으로 열리면서 컴퓨텅 리소스는 더이상 영속적이지 않는다.</strong>
데이터가 증가함에 따라 스케일아웃이 가능한 시스템이다.</p>
<p>데이터 중앙화 : <strong>카프카를 메시지 전달의 중앙 플랫폼으로 두고</strong>, 기업에서 필요한 모든 데이터 시스템(오라클, NOSQL, 하둡) 뿐만 아니라 마이크로 서비스, 사스 서비스 등과
<strong>연결된 파이프라인을 만드는 것을 목표</strong>로 두고 개발되었다.  </p>
<p><strong>[링크드인에서 카프카를 적용한 이후]</strong></p>
<p>사내 서비스에서 발생하는 모든 이벤트/데이터의 흐름을 중앙에서 관리한다.
<strong>카프카가 제공하는 데이터를 이용해서 다양한 분석이 가능</strong>해졌다.</p>
<p>개발 입장에서도 여러 데이터 시스템에 의존하지 않고, 카프카에만 데이터를 전달하면 되기 때문에 본연의 업무에만 집중할 수 있게됨</p>
<p><img src="https://velog.velcdn.com/images/data-traveler/post/03031c29-e6f6-4432-8742-d33aaa33b957/image.png" alt=""></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Elasticsearch] 자주 사용하는 명령어]]></title>
            <link>https://velog.io/@data-traveler/Elasticsearch-%EC%9E%90%EC%A3%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94-%EB%AA%85%EB%A0%B9%EC%96%B4</link>
            <guid>https://velog.io/@data-traveler/Elasticsearch-%EC%9E%90%EC%A3%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94-%EB%AA%85%EB%A0%B9%EC%96%B4</guid>
            <pubDate>Mon, 21 Mar 2022 10:38:46 GMT</pubDate>
            <description><![CDATA[<h1 id="elasticsearch-자주-사용하는-명령어">[Elasticsearch] 자주 사용하는 명령어</h1>
<h2 id="pending-task-확인">Pending task 확인</h2>
<ul>
<li>일반적인 상황에서는 empty list 반환</li>
<li>pending 되어 있는 작업이 있는 경우 그 리스트 반환</li>
</ul>
<pre><code class="language-bash">GET _cluster/pending_tasks</code></pre>
<h2 id="hot-threads-확인">hot threads 확인</h2>
<ul>
<li>GC가 비정상적이거나 CPU가 높거나 검색이 밀리는 등 대부분의 문제의 원인을 유추할 수 있음</li>
</ul>
<pre><code class="language-bash">GET _nodes/hot_threads?pretty

GET _nodes/node-01/hot_threads
GET _nodes/node-02/hot_threads
GET _nodes/node-03/hot_threads</code></pre>
<h2 id="cluster--node-상태-확인">Cluster &amp; Node 상태 확인</h2>
<pre><code class="language-sql">GET _cluster/health
GET /_cat/nodes

# curl 명령어
# 인증서 미적용
curl -i http://x.x.x.x:9202
curl -XGET &quot;x.x.x.x:9202/_cat/nodes?v&quot;
curl http://x.x.x.x:9202/_cluster/health

# 인증서 적용시
curl -i -k -u elastic https://x.x.x.x:9202
curl -k -u elastic -XGET &quot;https://x.x.x.x:9202/_cat/nodes?v&quot;
curl -k -u elastic https://x.x.x.x:9202/_cluster/health?pretty</code></pre>
<h2 id="index-정보-확인">Index 정보 확인</h2>
<pre><code class="language-bash"># 모든 인덱스 확인
GET _cat/indices?v&amp;s=index

# 특정 인덱스 확인
GET _cat/indices/hunet-app-b2b-2019-*?v&amp;s=index

# 인덱스 health 확인
GET _cat/indices?health=yellow

# 인덱스 생성
PUT travel-log
{
  &quot;settings&quot;: {
    &quot;index&quot;: {
      &quot;number_of_shards&quot;: &quot;3&quot;,
      &quot;number_of_replicas&quot;: &quot;1&quot;
    }
  },
  &quot;mappings&quot;: {
    &quot;properties&quot;: {
      &quot;start_date&quot;: {
        &quot;type&quot;: &quot;keyword&quot;
      },
      &quot;end_date&quot;: {
        &quot;type&quot;: &quot;keyword&quot;
      },
      &quot;place&quot;: {
        &quot;type&quot;: &quot;keyword&quot;
      },
      &quot;word&quot;: {
        &quot;type&quot;: &quot;keyword&quot;
      }
    }
  }
}

# 인덱스 내 데이터 검색
GET travel-log/_search
{
  &quot;query&quot;: {
    &quot;bool&quot;: {
      &quot;should&quot;: [
        { &quot;match_phrase&quot;: { &quot;word&quot;: &quot;여행&quot; } },
        { &quot;match_phrase&quot;: { &quot;word&quot;: &quot;제주도&quot; } },   
        { &quot;match_phrase&quot;: { &quot;word&quot;: &quot;바다&quot; } }
      ]
    }
  }
}

# 인덱스 내 데이터 삭제
POST travel-log/_delete_by_query?wait_for_completion=true
{
  &quot;query&quot;: {
    &quot;bool&quot;: {
      &quot;should&quot;: [
        { &quot;match_phrase&quot;: { &quot;word&quot;: &quot;여행&quot; } },
        { &quot;match_phrase&quot;: { &quot;word&quot;: &quot;제주도&quot; } },   
        { &quot;match_phrase&quot;: { &quot;word&quot;: &quot;바다&quot; } }
      ]
    }
  }
}</code></pre>
<h2 id="template-정보-확인">template 정보 확인</h2>
<pre><code class="language-bash"># 전체 template 확인
GET _cat/templates?v&amp;s=name

# 특정 template 상세정보
GET _template/travel-log-template

# default template 확인
GET _template/default

# template 삭제
DELETE _template/travel-log-template
l
# template 생성
PUT _template/travel-log-template
{
  &quot;order&quot;: 2,
  &quot;index_patterns&quot;: [
    &quot;travel-log-*&quot;
  ],
  &quot;settings&quot;: {
    &quot;index&quot;: {
      &quot;number_of_shards&quot;: &quot;3&quot;,
      &quot;number_of_replicas&quot;: &quot;1&quot;
    }
  },
  &quot;mappings&quot;: {
    &quot;dynamic_templates&quot;: [
      {
        &quot;strings_as_keywords&quot;: {
          &quot;mapping&quot;: {
            &quot;type&quot;: &quot;keyword&quot;
          },
          &quot;match_mapping_type&quot;: &quot;string&quot;
        }
      }
    ]
  },
  &quot;aliases&quot;: {}
}

# ilm template 생성
PUT _template/daily-log-template
{
  &quot;order&quot;: 2,
  &quot;index_patterns&quot;: [
    &quot;daily-log-*&quot;
  ],
  &quot;settings&quot;: {
    &quot;index&quot;: {
      &quot;number_of_shards&quot;: &quot;3&quot;,
      &quot;number_of_replicas&quot;: &quot;1&quot;,
      &quot;lifecycle&quot;: {
        &quot;name&quot;: &quot;daily-log-lim&quot;,
        &quot;rollover_alias&quot;: &quot;daily-log&quot;
      }
    }
  },
  &quot;mappings&quot;: {
    &quot;dynamic_templates&quot;: [
      {
        &quot;strings_as_keywords&quot;: {
          &quot;mapping&quot;: {
            &quot;type&quot;: &quot;keyword&quot;
          },
          &quot;match_mapping_type&quot;: &quot;string&quot;
        }
      }
    ]
  }
}</code></pre>
<h2 id="샤드-할당-확인-및-강제-할당">샤드 할당 확인 및 강제 할당</h2>
<pre><code class="language-bash">GET /_cluster/allocation/explain

POST /_cluster/reroute?retry_failed=true</code></pre>
<h2 id="스냅샷">스냅샷</h2>
<pre><code class="language-bash"># 스냅샷 확인
GET /_snapshot
GET /_snapshot/*20210612
GET /_snapshot/_all

# 스냅샷 리스트 및 스냅샷 시작/종료시간 확인
GET _snapshot/all_backup/all_backup_20210513

# 스냅샷 진행 상태
GET _snapshot/all_backup/all_backup_20210513/_status

# 스냅샷 삭제(종료)
DELETE _snapshot/all_backup/all_backup_20210513

# 스냅샷 확인
GET _snapshot/travel-log-20210714/_all

# 복원
POST _snapshot/travel-log-20210714/travel-log-2021.07.28/_restore?wait_for_completion=false
{
  &quot;indices&quot;: [&quot;travel-2021.07.28&quot;]
}

# 복원 확인
GET _cat/recovery/lms-app-logging-audit-2020.07.28?v</code></pre>
<h2 id="task">Task</h2>
<pre><code class="language-bash"># 실행중인 Task 확인
GET _tasks
GET _cat/tasks?v
GET _tasks?nodes=node-1, node-2
GET _tasks/vIYMDSJ3TGCGFtcu3Btp6w:521843726
GET _cat/tasks?detailed
GET _tasks?actions=*reindex
GET _tasks?actions=*reindex&amp;wait_for_completion=true&amp;timeout=10s

# Task 취소
POST _tasks/vIYMDSJ3TGCGFtcu3Btp6w:521843726/_cancel</code></pre>
<p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.8/tasks.html#task-cancellation">Task Management API | Elasticsearch Reference [6.8] | Elastic</a></p>
<h2 id="index-open--close">Index open &amp; close</h2>
<pre><code class="language-bash">POST travel-log/_close
POST travel-log/_open</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Logstash] Elasticsearch 와 RDBMS 연동]]></title>
            <link>https://velog.io/@data-traveler/Logstash-Elasticsearch-%EC%99%80-RDBMS-%EC%97%B0%EB%8F%99</link>
            <guid>https://velog.io/@data-traveler/Logstash-Elasticsearch-%EC%99%80-RDBMS-%EC%97%B0%EB%8F%99</guid>
            <pubDate>Mon, 21 Mar 2022 10:31:25 GMT</pubDate>
            <description><![CDATA[<h1 id="logstash-elasticsearch-와-rdbms-연동">[Logstash] Elasticsearch 와 RDBMS 연동</h1>
<p>Kibana &gt; Stack Management &gt; Logstash Pipelines</p>
<pre><code class="language-json">input {
    jdbc {
        jdbc_driver_library =&gt; &quot;/usr/share/java/mysql-connector-java.jar&quot;
        jdbc_driver_class =&gt; &quot;com.mysql.jdbc.Driver&quot;
        jdbc_connection_string =&gt; &quot;jdbc:mysql://x.x.x.x:3011/Travel&quot;
        jdbc_user =&gt; &quot;id&quot;
        jdbc_password =&gt; &quot;pwd&quot;
        statement_filepath =&gt; &quot;/home/hunetdb/logstash/config/conf_sql/searchengine_travel.sql&quot;
        schedule =&gt; &quot;30 03,12 * * *&quot;
        type =&gt; &quot;search-engine-travel&quot;
    }
}

filter {
    if [type] == &quot;search-engine-travel&quot; {
        mutate {
            remove_field =&gt; &quot;message&quot;
        }
    ruby {
            init =&gt; &quot;require &#39;time&#39;&quot;
            code =&gt; &quot;event.set(&#39;indexDate&#39;, Time.now.utc.getlocal.strftime(&#39;%Y.%m.%d&#39;))&quot;
        }
    }
}

output {
    if [type] == &quot;search-engine-travel&quot; {
        elasticsearch {
            hosts =&gt; [&quot;x.x.x.10:9200&quot;, &quot;x.x.x.11:9200&quot;, &quot;x.x.x.12:9200&quot;]
            index =&gt; &quot;search-engine-travel-%{indexDate}&quot;
            document_id =&gt; &quot;%{travel_seq}&quot;
            user =&gt; &quot;elastic&quot;
            password =&gt; &quot;${elastic}&quot;
            ssl =&gt; true
            ssl_certificate_verification =&gt; false
        }
    }
}</code></pre>
<ul>
<li><p>input : 어떤 데이터를 수집할지 설정하는 부분</p>
<ul>
<li><p>jdbc_driver_library : 사용하는 jdbc driver 위치 설정</p>
</li>
<li><p>jdbc_driver_class : 사용하는 jdbc driver 명시</p>
</li>
<li><p>jdbc_connection_string : 사용하는 db 종류, db가 위치한 host, db 이름 설정</p>
<p>  ex) jdbc:mysql://x.x.x.x:3011/Travel</p>
<ul>
<li>db 종류 : mysql</li>
<li>db host : x.x.x.x:3011</li>
<li>db 이름 : Travel</li>
</ul>
</li>
<li><p>jdbc_user &amp; jdbc_password : db 서버에서 권한을 부여 받은 id와 password</p>
</li>
<li><p>statement_filepath : db에서 어떤 query 및 프로시저를 실행할지 작성한 파일의 경로</p>
</li>
</ul>
</li>
<li><p>filter : 수집한 데이터를 가공</p>
</li>
<li><p>output : 수집한 데이터를 전송</p>
<ul>
<li><p>hosts : 데이터를 저장할 Elasticsearch의 Host</p>
</li>
<li><p>index : Elasticsearch Host의 어떤 Index에 저장할지 설정 (없으면 생성)</p>
</li>
<li><p>document_id : Document ID를 직접 지정</p>
<ul>
<li><p>미지정시 Elasticsearch가 임의값으로 생성</p>
</li>
<li><p>Document ID가 같으면 Update, 없으면 Insert</p>
<p><a href="https://www.elastic.co/kr/blog/how-to-keep-elasticsearch-synchronized-with-a-relational-database-using-logstash">Logstash와 JDBC를 사용해 RDBMS와 Elasticsearch의 동기화를 유지하는 방법</a></p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Elasticsearch] Node Start and Stop]]></title>
            <link>https://velog.io/@data-traveler/Elasticsearch-Node-Start-and-Stop</link>
            <guid>https://velog.io/@data-traveler/Elasticsearch-Node-Start-and-Stop</guid>
            <pubDate>Mon, 21 Mar 2022 10:03:15 GMT</pubDate>
            <description><![CDATA[<h1 id="elasticsearch-node-start-and-stop">[Elasticsearch] Node Start and Stop</h1>
<p>Elasticsearch Node를 재시작 할 때 아래와 같은 방법으로 작업을 진행하여야 샤드들이 재배치 되지 않고 빠르게 재시작 할 수 있음</p>
<h2 id="shard-allocation-stop">Shard Allocation Stop</h2>
<ul>
<li>노드를 중단했을 때 샤드들이 재배치 되지 않게 다음 명령 실행</li>
</ul>
<pre><code class="language-bash"># Kibana Dev Tool 에서 실행
PUT _cluster/settings {
    &quot;persistent&quot;: { &quot;cluster.routing.allocation.enable&quot;: &quot;none&quot;
    } 
}</code></pre>
<h2 id="sync-flus">Sync Flus</h2>
<ul>
<li>Primary - Replica 샤드들 간의 세그먼트 저장 상태를 동기화 시켜줌</li>
</ul>
<pre><code class="language-bash"># Kibana Dev Tool 에서 실행
POST _flush/synced</code></pre>
<h2 id="stop-node">Stop Node</h2>
<ul>
<li>노드가 중단되면 Elasticsearch 상태가 Yellow 로 변경됨</li>
<li>노드 시작과 종료를 쉘 스크립트 <a href="http://start.sh">start.sh</a> 파일과 <a href="http://stop.sh">stop.sh</a> 파일로 생성해놓아서 해당 파일만 실행하면 간편하게 Node 시작/중지를 할 수 있음</li>
</ul>
<pre><code class="language-bash"># Elasticsearch 디렉토리 접속

# Elasticsearch 중지
$ sh stop.sh</code></pre>
<h2 id="start-work">Start Work</h2>
<ul>
<li><p>필요한 작업 진행</p>
<p>  ex) JVM heap size 변경, 롤링 업그레이드 등</p>
</li>
</ul>
<h2 id="start-node">Start Node</h2>
<pre><code class="language-bash"># Elasticsearch 디렉토리 접속
$ cd /home/dohyung/elasticsearch

# Elasticsearch 시작
$ sh start.sh</code></pre>
<h2 id="node-확인">Node 확인</h2>
<pre><code class="language-bash"># Kibana Dev Tool 에서 실행
GET _cat/nodes</code></pre>
<h2 id="shard-allocation-start">Shard Allocation Start</h2>
<ul>
<li>unassigned 된 샤드들이 새 노드들에 다시 배치될 수 있게 다음 명령 실행</li>
</ul>
<pre><code class="language-bash"># Kibana Dev Tool 에서 실행
PUT _cluster/settings {
    &quot;persistent&quot;: { &quot;cluster.routing.allocation.enable&quot;: null
    } 
}</code></pre>
<h2 id="cluster-health-chedk">Cluster health chedk</h2>
<p>Elasticsearch 클러스터가 Green 상태가 될 때까지 기다림</p>
<pre><code class="language-bash"># Kibana Dev Tool 에서 실행
GET _cat/health</code></pre>
]]></description>
        </item>
    </channel>
</rss>