'Elastic'에 해당되는 글 498건

  1. 2015.08.17 [Elasticsearch] Scripting 을 이용한 Field Value 조작하기.
  2. 2015.08.12 [Elasticsearch] Test Code 작성용 템플릿 Class.
  3. 2015.08.12 [Elasticsearch] 실행 및 중지 스크립트 테스트용.
  4. 2015.08.06 [Kibana] Kibana 에서 Index Alias 사용하기
  5. 2015.07.29 [Kibana4.x] Value format 설정하기
  6. 2015.07.29 [Kibana4.x] 생성한 dashboard export & import 하기.
  7. 2015.07.29 [Logstash] logstash 개발 및 디버그 시 유용한 설정
  8. 2015.07.08 [Elasticsearch] 매일 보는 페이지.
  9. 2015.07.03 [Elasticsearch] shard allocation 운영 테스트용 REST 코드 - 1.6.0 이상.
  10. 2015.07.02 [Elasticsearch] shard allocation 운영 테스트용 REST 코드

[Elasticsearch] Scripting 을 이용한 Field Value 조작하기.

Elastic/Elasticsearch 2015. 8. 17. 14:59

정확하게 조작한다기 보다 저장된 document 의 field value 를 이용한다가 맞을 것 같습니다.

기본 참조 문서는 아래와 같습니다.

https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html


문서를 보셨으면 아시겠지만 기본 groovy 를 사용하게 되어 있습니다.

하지만 보안 이슈로 설정이 기본 false 입니다.

아래와 같이 설정을 변경해 주셔야 사용이 가능 합니다.


[Scripting Enable]

script.inline: on

또는

script.groovy.sandbox.enabled: true

※ 관련 설정에 대한 자세한 내용은 문서를 참고 하시면 됩니다.


아래는 문서 내용 snippet 입니다.


ValueDescription

off

scripting is turned off completely, in the context of the setting being set.

on

scripting is turned on, in the context of the setting being set.

sandbox

scripts may be executed only for languages that are sandboxed

그리고 추후 2.0.0 에서는 위 설정에서 groovy sandbox 는 deprecated 예정이니 참고하세요.

(https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html#_groovy_sandboxing)


설정을 해주셨으니 이제 value 에 접근하는 방법에 대해서 알아 보겠습니다.

문서에서는 총 3 가지 방법을 제시해 주고 있습니다.


[Value 접근]

# Document fields

_doc['field_name'].value or values


# Stored fields

_fields['field_name'].value


# Source field

_source['field_name']


※ 여기서 _fields 는 store 옵션을 true 로 하지 않으셨다면 에러가 발생 합니다.


value에 접근 하는 방법을 아셨으니 이 값을 이용한 연산을 어떻게 하는지도 궁금하실 겁니다.

위에서 말씀 드렸듯이 기본적인 language 는 groovy 입니다.

그렇기 때문에 groovy script 를 이용해서 연산 및 처리를 하시면 되겠습니다.


아래는 substring에 대한 커뮤니티의 질문에 대한 예제 코드 입니다.


[script_fields 샘플코드]

GET /test_index/_search

{

    "script_fields": {

        "field1_substring": {

            "script": "_doc['field1'].value"

        }

    }

}


GET /test_index/_search

{

    "script_fields": {

        "field1_substring": {

            "script": "_fields['field1'].value.substring(0, 5)"

        }

    }

}


GET /test_index/_search

{

    "script_fields": {

        "field1_substring": {

            "script": "_source.field1.substring(3, 10)"

        }

    }

}


※ script_fields 를 이용하게 되면 return 시 fields를 통해서 정보가 전달 됩니다. (즉, 필요한 field 가 있다면 추가로 선언해 주셔야 한다는 이야기 입니다.)

※ QueryDSL 을 보시면 아시겠지만 기본 query 구문이 없으면 match_all 로 동작 합니다.

※ 추가적으로 주의 할 점은 field 속성이 not_analyzed 인지 analyzed, store 인지 아닌지 확인 하시고 테스트 하시기 바랍니다.


:

[Elasticsearch] Test Code 작성용 템플릿 Class.

Elastic/Elasticsearch 2015. 8. 12. 10:52

정말 단순히 제가 테스트 할 때 필요해서 기록해 두는 겁니다. ^^;

별로 도움 안될 확율이 높으니 관심있게 보지 마세요.


/**
 * Created by hwjeong
 * 이 템플릿은 Elasticsearch Test Code를 작성하는데 기본으로 사용하기 위해 작성 하였습니다.
 * 사용 방법은 두 가지 입니다.
 * settings.put("cluster.name", "elasticsearch") 를 통해서 기본적으로 구성 및 등록할 클러스터를 생성합니다.
 * settings.put("path.data", "data/index") 정보는 local 테스트 시 색인 데이터를 어디에 저장할지 설정을 하게 됩니다.
 *      client 노드를 구성해서 테스트를 할거라면 생성한 프로젝트 root 경로 아래 data/index 라는 폴더가 생성이 됩니다.
 * nodeBuilder를 통해서 테스트 및 생성할 노드의 특성을 정의 할 수 있습니다.
 *  .data(true) 설정 시 작성하시는 노드는 데이터 노드의 특성을 갖습니다.
 *  .local(true) 설정 시 같은 머신의 jvm 내부 노드간 통신이 이루어 지며 다른 jvm 노드간에는 통신이 되지 않습니다.
 *      false 로 설정 시 네트워크 분리가 되어 있지 않을 경우 운영 서버나 다른 클러스터 군으로 연결 되는 것을 주의 하셔야 합니다.
 *  .client(true)
 *      true 라는 의미는 client node 로 사용하겠다는 의미 이며, 어떠한 data 도 저장 하지 않겠다는 것입니다.
 *      즉, node.data 가 false 로 설정 되는 것과 같습니다.
 */
public class EsTestTemplate {

private static final Logger log = LoggerFactory.getLogger(EsTestTemplate.class);

private ImmutableSettings.Builder settings;
private Node node;
private Client client;

@Before
public void setup() throws Exception {
settings = ImmutableSettings.settingsBuilder();
settings.put("cluster.name", "elasticsearch");
// settings.put("node.name", "testNode");
// settings.put("path.data", "data/index");
// settings.put("gateway.type", "none");

node = NodeBuilder.nodeBuilder()
.settings(settings)
.data(true)
.local(false)
.client(false)
.node(); // included start() method.

client = node.client();
}

@After
public void tearDown() throws Exception {
client.close();
node.close();
}
}


※ 코드는 그냥 단순 nodebuilder 를 이용해서 테스트용 node 를 하나 생성 하거나 client를 생성 하는 내용입니다.


:

[Elasticsearch] 실행 및 중지 스크립트 테스트용.

Elastic/Elasticsearch 2015. 8. 12. 10:27

역시나 또 자꾸 까먹어서.. ^^

elasticsearch 뿐만 아니라 기타 다른 프로그램을 실행 시키고 중지 시킬 때 활용 하시면 됩니다.


[start.sh]

#!/bin/bash


DIR_NAME=`dirname "$0"`

DIR_HOME=`cd $DIR_NAME; cd ..; pwd`


$DIR_HOME/bin/elasticsearch > /dev/null 2>&1 & ES_PID=$!

echo $ES_PID > $DIR_HOME/bin/elasticsearch_daemon.pid


[stop.sh]

#!/bin/bash


DIR_NAME=`dirname "$0"`

DIR_HOME=`cd $DIR_NAME; cd ..; pwd`


ES_PID=`cat $DIR_HOME/bin/elasticsearch_daemon.pid`

kill -9 $ES_PID

echo "Elasticsearch Daemon($ES_PID) is killed"

rm -f $DIR_HOME/bin/elasticsearch_daemon.pid


참고로 위 실행 스크립트는 설정 최적화나 뭐 그런건 없습니다.

단순 테스트 좀 빨리 해보기 위해서 copy & paste 의 시간 절약용 입니다. :)

:

[Kibana] Kibana 에서 Index Alias 사용하기

Elastic/Kibana 2015. 8. 6. 18:38

보통 ELK 조합으로 처음 사용하시는 분들의 경우 index 수가 많아 질 수록 kibana chart 생성이 느려 지거나 shard failed  같은 메시지를 경험 하실수 있을 텐데요.


이유는 아주 가까운 곳에 있습니다.

이미 아시는 분들도 많을 테지만 첨 접하시는 분들에게는 유용할 수 있으니 올려 보겠습니다.


기본적으로 logstash를 사용하면 time based 로 index 가 생성 됩니다.

보통 아래와 같은 패턴으로 정의 됩니다.

logstash-%{+YYYY.MM.dd}


위와 같이 정의가 되어 있기 때문에 kibana 에서는 아래와 같이 설정이 되는데요.

logstash-*

- Settings -> Indices 에 있습니다.


즉, 이렇게 설정이 되기 때문에 생성된 모든 index 를 대상으로 질의를 하게 됩니다.

그럼 어떤 문제들이 발생 할지 예측 가능 하시겠죠.


전체 index를 대상으로 질의를 하기 때문에 search thread 가 생성되어 있는 shard 수 만큼 실행 되게 됩니다.

결국 시스템 리소스는 쭈욱 올라갈거고 이렇게 되다 보면 timeout 등이 발생을 하게 될 겁니다.

결국 shard failed 현상이 나오게 되는 것입니다.


이런 문제를 해결 하기 위해서는 index aliases 기능을 활용 하시면 됩니다.

어차피 보고 싶은 정보는 최신 정보이기 때문에 latest index 에 대해서만 alias 를 생성해 주시고 chart 및 dashboard 생성 시 생성한 alias 를 대상으로 만들어 주시면 됩니다.

하지만 하루가 지나면 alias 를 다시 latest index 를 바라 볼 수 있도록 바꿔 줘야 하기 때문에 이런 부분은 관리 기능을 만들어서 사용하시면 별 문제 없이 지속적으로 사용을 하실 수 있을 것입니다.


[Index Aliases]

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html


:

[Kibana4.x] Value format 설정하기

Elastic/Kibana 2015. 7. 29. 17:46

kibana를 이용하다 보면 화면에 보여지는 값에 대한 format 을 고치고 싶은 욕구가 생깁니다.

이걸 어디서 고쳐줘야 하나 싶은데 역시 매뉴 몇번 눌러 보면 찾을 수 있습니다.

귀찮아 하시는 분들을 위해 공유해 봅니다.


[참고문서]

https://www.elastic.co/blog/kibana-4-1-field-formatters


[매뉴 tree]

## Global 설정

GNB -> Settings -> Advanced


## 특정 인덱스의 field format을 바꾸고 싶을 경우

GNB -> Settings -> Indices -> Select Index Patterns -> controls 컬럼에서 수정하고자 하는 field 클릭


[Advanced 화면]



:

[Kibana4.x] 생성한 dashboard export & import 하기.

Elastic/Kibana 2015. 7. 29. 17:40

매뉴만 몇번 눌러 보시면 다 아시는 내용인데요.

눌러 보기 귀찮아 하시는 분들도 있을 것 같아 걍 올려 봅니다.


간혹 작성한 kibana dashboard를 export 받고 싶거나 import 받고 싶을 때가 있습니다.

근데 이거 어디서 백업을 받을 수 있지 하고 찾으면 잘 안찾아 지죠.


아래 페이지에서 export & import 받을 수 있으니 참고하세요.


[매뉴 tree]

GNB -> Settings -> Objects


[매뉴]



:

[Logstash] logstash 개발 및 디버그 시 유용한 설정

Elastic/Logstash 2015. 7. 29. 17:32

제목 쓰기가 참 어렵내요.

logstash를 많이 사용해 보신 분들은 다들 잘 아실 것 같습니다.


저 같은 경우 output 은 거의 elasticsearch를 사용하고 있기 때문에 개발 시 디버깅을 위해서 아래 설정을 많이 이용합니다.


[디버그용 설정]

input {

  http {

    port => 8080

    codec => json_lines {}

  }

}


output {

  stdout {

    codec => rubydebug

  }

}


[디버그용 로그 스태쉬 실행]

$ bin/logstash -e "input { http { port => 8080 codec => json_lines {} } } output { stdout { codec => rubydebug } }"


잘 아시겠지만 output 은 여러개를 지정해 줄 수 있습니다.

실제 elasticsearch로도 색인을 하고 싶으시다면 아래와 같이 하시면 되겠죠.


[ouput - elasticsearch + stdout]

output {

  elasticsearch {

    cluster => "xxxxxx"

    bind_host => "localhost"

    bind_port => "9300"

    protocol => "transport"

    index => "logstash-%{+YYYY.MM.dd}"

  }

  stdout {

    codec => rubydebug

  }

}


:

[Elasticsearch] 매일 보는 페이지.

Elastic/Elasticsearch 2015. 7. 8. 10:44

elasticsearch 를 주 업으로 삼으면서 매일 보는 페이지들 입니다.


https://www.elastic.co/blog

https://github.com/elastic/elasticsearch/issues

https://www.elastic.co/guide/en/elasticsearch/resiliency/current/index.html


아주 유용한 정보들이 많이 들어 있고 어떻게 발전해 가는지도 확인이 가능 합니다.

:

[Elasticsearch] shard allocation 운영 테스트용 REST 코드 - 1.6.0 이상.

Elastic/Elasticsearch 2015. 7. 3. 13:59

작성하고 보니 최신 내용을 반영할걸 이라는 후회가 밀려 오내요.

이전 글 http://jjeong.tistory.com/1034 이거는 사실 deprecated 예정입니다.

코드에도 명시되어 있어서.. ^^;;


아래 코드로 변경 합니다.

참고하세요.


curl -XPUT localhost:9200/_cluster/settings -d '{

    "persistent" : {

        "cluster.routing.allocation.enable" : "primaries",

        "cluster.routing.allocation.allow_rebalance" : "indices_all_active",

        "cluster.routing.allocation.cluster_concurrent_rebalance" : 2,

        "cluster.routing.allocation.node_initial_primaries_recoveries" : 4,

        "cluster.routing.allocation.node_concurrent_recoveries" : 2

    }

}'

※ 위 값들은 default 값입니다. "primaries" 만 빼고요 ^^


상세 내용을 확인 하고 싶으신 분들은 아래 문서를 참고하시길 바랍니다.


https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-cluster.html#shards-allocation


그냥 넘어 갈라고 했지만...


▷ cluster.routing.allocation.allow_rebalance

설명에 있지만 이건 shard rebalance에 대한 설정 입니다.

아래 값들에 대한 조건일 때 rebalance 하겠다는 것으로 이해 하시면 됩니다.

always : 항상 할 거다.

indices_primaries_active : primary shard 가 올라 오면 할 거다.

indices_all_active : 전체 shard 가 올라 오면 할 거다.


당연히 indices_all_active 가 default 설정이 되겠죠.


▷ cluster.routing.allocation.cluster_concurrent_rebalance

클러스터를 통틀어서 동시에 rebalance 할 shard 수를 제한 하는 설정 입니다.

기본은 2개로 설정 되어 있습니다.


▷ cluster.routing.allocation.node_initial_primaries_recoveries

각 노드 당 primary shard recovery에 대한 초기 크기를 설정 하는 것입니다.

기본은 4개로 설정 되어 있습니다.


▷ cluster.routing.allocation.node_concurrent_recoveries

노드에서 동시에 수행할 recovery 크기를 설정 하는 것입니다.


▷ cluster.routing.allocation.enable

이게 이전에 deprecated 된 설정의 확장인데요. (위에 설정도 포함 이지만..)

shard 종류에 따라 어떻게 처리 할 것인지를 결정 하게 합니다.

all : 몽땅 다 하겠다.

primaries : primary shard 만 하겠다.

new_primaries : 새로 생성한 인덱스의 primary shard 만 하겠다.

none : 몽땅 다 안하겠다.


딱 보면 disable_allocation:true = primaries + none 정도로 보면 쉽쥬.

반대는 disable_allocation:false = all 정도로 보면 쉽쥬.


:

[Elasticsearch] shard allocation 운영 테스트용 REST 코드

Elastic/Elasticsearch 2015. 7. 2. 18:18
매번 작성 하기 귀찮아서 그냥 남겨 봅니다.

[shard allocation disable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "persistent" : {
    "cluster.routing.allocation.disable_allocation" : true
    }
}'

[모든 종류의 shard allocation disable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "transient" : {
        "cluster.routing.allocation.enable" : "none"
    }
}'

[shard allocation enable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "persistent" : {
    "cluster.routing.allocation.disable_allocation" : false
    }
}'

[모든 종류의 shard allocation enable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "transient" : {
        "cluster.routing.allocation.enable" : "all"
    }
}'

[모든 인덱스의 replica shard disable]
curl -XPUT localhost:9200/*/_settings -d '{"number_of_replicas":0}'



: