'Index'에 해당되는 글 15건

  1. 2014.01.08 [Elasticsearch] template 생성 힌트.
  2. 2014.01.08 [elasticsearch] 색인 생성 스크립트.
  3. 2013.09.17 [Elasticsearch] Bulk Indexing 후 Data Consistency 관리.
  4. 2013.04.08 [elasticsearch] Java API : Index
  5. 2013.01.16 elasticsearch 색인 생성 스크립트 예제

[Elasticsearch] template 생성 힌트.

Elastic/Elasticsearch 2014. 1. 8. 18:33

아래 글 참고

http://jjeong.tistory.com/914


이해하기 쉽도록 힌트 몇자 적습니다.

기본 이해는

http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-templates.html

이 문서를 보시면 됩니다.


step 1.

template 을 생성 합니다.

curl -XPUT localhost:9200/_template/template_1 -d '
{
   
"template" : "te*",
   
"settings" : {
       
"number_of_shards" : 1
   
},
   
"mappings" : {
       
"type1" : {
           
"_source" : { "enabled" : false }
       
}
   
}
}
'

여기서 template : te* 이 의미 하는 것은 index 명입니다.


step 2.

curl -XPUT 'http://localhost:9200/temp/'

이렇게 생성하면 temp 라는 인덱스의 settings/mappings 정보는 template_1 값을 가지게 됩니다.


logstash 예제로 보겠습니다.

아래는 template 생성용 json 입니다.

{
  "template" : "logstash-*",
  "settings" : {
    "index.refresh_interval" : "5s",
    "analysis" : {
      "analyzer" : {
        "default" : {
          "type" : "standard",
          "stopwords" : "_none_"
        }
      }
    }
  },
  "mappings" : {
    "_default_" : {
       "_all" : {"enabled" : true},
       "dynamic_templates" : [ {
         "string_fields" : {
           "match" : "*",
           "match_mapping_type" : "string",
           "mapping" : {
             "type" : "multi_field",
               "fields" : {
                 "{name}" : {"type": "string", "index" : "analyzed", "omit_norms" : true, "index_options" : "docs"},
                 "{name}.raw" : {"type": "string", "index" : "not_analyzed", "ignore_above" : 256}
               }
           }
         }
       } ],
       "properties" : {
         "@version": { "type": "string", "index": "not_analyzed" },
         "geoip" : {
           "type" : "object",
             "dynamic": true,
             "path": "full",
             "properties" : {
               "location" : { "type" : "geo_point" }
             }
         }
       }
    }
  }
}

보시면 인덱스 명이 logstash-* 로 시작하는 것들은 이 템플릿을 따르게 됩니다.

_all 을 enable 한 이유는 특정 필드에 대해서 동적으로 검색을 지원하기 위해서 라고 보시면 됩니다.

특히 string 필드에 대해서는 검색을 하는 것으로 지정을 하였고, multi_field 구성한 이유는 not_analyzed 로 봐서는 facet 기능이나 sort 등의 다른 기능을 활용하기 위해서 인것으로 보입니다.


그럼 이만... :)

:

[elasticsearch] 색인 생성 스크립트.

Elastic/Elasticsearch 2014. 1. 8. 12:08

색인 스키마를 json 파일로 만들어 놓고 rest api 로 생성 할 때 유용한 스크립트 입니다.

그냥 제가 사용하기 편할라고 대충 만들어 놓은거랍니다.


#!/bin/bash

size=$#

if [ $size -ne 3 ]; then
    echo "Usage: create_index.sh IP:PORT INDICE SCHEME_FILE";
    echo "Example: create_index.sh localhost:9200 idx_local schema.json";
    exit 0;
fi

serviceUri=$1
indice=$2
schema=$3

curl -XDELETE 'http://'$serviceUri'/'$indice

curl -XPUT 'http://'$serviceUri'/'$indice -d @$schema


:

[Elasticsearch] Bulk Indexing 후 Data Consistency 관리.

Elastic/Elasticsearch 2013. 9. 17. 12:35

벌크 인덱싱 후 간혹 샤드간에 데이터가 왔다 갔다 할 때가 있습니다.

이건 elasticsearch 색인이 잘못 되었다고 보시면 안됩니다.

인덱스와 샤드의 status 정보를 보면

- num_docs

- max_docs

- deleted_docs

이런게 있죠.


기본적으로 벌크 색인 시 empty index 에 색인을 하게 될 텐데요.

색인 도중 문제가 발생해서 일부 색인 데이터가 들어가고 다시 같은 인덱스에 색인을 하게 되면  updateDocument 를 실행 하게 됩니다.

뭐 루씬 API 보시면 이제 add/update 가 하나의 API 로 동작 하긴 합니다.

암튼 이렇게 되다 보니 deleted_docs 가 발생 하게 되고 num_docs 와 max_docs 수치가 안맞게 됩니다.

즉, num_docs = max_docs - deleteed_docs 와 같습니다.


이런 관계로 색인 완료 시 recovery 또는 optimize 작업을 통해서 data consistency 를 보정해 주어야 합니다.

그럼 이걸 어떻게 할까요?


아래 명령어로 해보시고  ES  API 문서 참고 하시면 되겠습니다.

(거의 대부분 default value 입니다.)


[Java API]

new OptimizeRequest()

    .indices(indice)

    .flush(true)

    .onlyExpungeDeletes(false)

    .refresh(true)

    .waitForMerge(true)

    .operationThreading(BroadcastOperationThreading.THREAD_PER_SHARD)

    .maxNumSegments(1)



[Rest API]

curl -XPOST 'http://localhost:9200/indice/_optimize?only_expunge_deletes=false&max_num_segments=1&refresh=true&flush=true&wait_for_merge=true'



[Recovery]

curl -XPOST 'http://localhost:9200/indice/_close'

curl -XPOST 'http://localhost:9200/indice/_open'


client.admin()

    .indices()

    .close(new CloseIndexRequest("indice"));


client.admin()

    .indices()

    .close(new OpenIndexRequest("indice"));



[Reference]

http://www.elasticsearch.org/guide/reference/api/admin-indices-optimize/

http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close/


:

[elasticsearch] Java API : Index

Elastic/Elasticsearch 2013. 4. 8. 18:42

본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며,

정보 교환이 목적입니다.


잘못된 부분에 대해서는 지적 부탁 드립니다.

(예시 코드는 성능 및 보안 검증이 되지 않았습니다.)



[elasticsearch java api 리뷰]

원문 링크 : http://www.elasticsearch.org/guide/reference/java-api/index_/


json document 를 생성하는 몇 가지 방법을 설명하고 있습니다.

There are different way of generating JSON document:


- Manually (aka do it yourself) using native byte[] or as a String

- Using Map that will be automatically converted to its JSON equivalent

- Using a third party library to serialize your beans such as Jackson

- Using built-in helpers XContentFactory.jsonBuilder()


위 방법들 중에서 제일 아래 elasticsearch helper 를 이용한 방법을 테스트해 봅니다.


우선 간단하게 index 와 index type 을 정의해 보도록 하겠습니다.

curl -XPUT 'http://localhost:9200/facebook' -d '{

    "settings" : { 

        "number_of_shards" : 5,

        "number_of_replicas" : 1  

    },  

    "mappings" : { 

        "post" : { 

            "properties" : { 

                "docid" : { "type" : "string", "store" : "yes", "index" : "not_analyzed" },

                "title" : { "type" : "string", "store" : "yes", "index" : "analyzed", "term_vector" : "yes", "analyzer" : "standard" }

            }   

        }   

    }   

}'


- index 는 facebook 으로 생성을 하고

- index type 은 post 라고 생성을 합니다.

- settings 와 mappings 에 대한 상세한 내용은 아래 링크 참고 하시기 바랍니다.

http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index/

http://www.elasticsearch.org/guide/reference/index-modules/

http://www.elasticsearch.org/guide/reference/mapping/

http://www.elasticsearch.org/guide/reference/mapping/core-types/


index, index type 생성이 끝났으면 이제 색인을 해보도록 하겠습니다

// 생성할 문서가 아래와 같다고 가정

// curl -XPUT 'http://localhost:9200/facebook/post/1' -d '{ "docid" : "henry", "title" : "This is the elasticsearch hadoop test." }'

// curl -XPUT 'http://localhost:9200/facebook/post/2' -d '{ "docid" : "henry", "title" : "elasticsearch test." }'

// curl -XPUT 'http://localhost:9200/facebook/post/3' -d '{ "docid" : "howook", "title" : "hadoop test." }'

// curl -XPUT 'http://localhost:9200/facebook/post/4' -d '{ "docid" : "howook", "title" : "test." }'


    IndexRequestBuilder requestBuilder;

    IndexResponse response;

        

    requestBuilder = client.prepareIndex("facebook", "post");

        

// setSource parameter 로 json string 형태로 등록

    requestBuilder.setId("1");

    requestBuilder.setSource("{ \"docid\" : \"henry\", \"title\" : \"This is the elasticsearch hadoop test.\" }");

    response = requestBuilder.execute().actionGet();


// XContentBuilder 로 setSource 전달

    XContentBuilder jsonBuilderDocument = jsonBuilder().startObject();

        jsonBuilderDocument.field("docid", "henry");

        jsonBuilderDocument.field("title", "elasticsearch test.");

    jsonBuilderDocument.endObject();

        

    requestBuilder.setId("2");

    requestBuilder.setSource(jsonBuilderDocument);

    response = requestBuilder.execute().actionGet();


- IndexRequestBuilder 의 setSource 에 대한 코드를 보시면 어떤 arguments 받는지 알 수 있습니다.

- 그리고 문서 색인에 사용되는 여러가지 다양항 옵션들은 아래 링크를 참고 하시기 바랍니다.

http://www.elasticsearch.org/guide/reference/api/index_/


아래는 index 생성 시 필요한 settings 와 mappings 에 대한 예제 코드 입니다.

맛보기 참고용 입니다.

IndicesAdminClient indices = client.admin().indices();

CreateIndexRequest indexRequest = new CreateIndexRequest("INDEX_NAME");

    indexRequest

        .settings(jsonBuilderIndexSetting)

        .mapping("INDEX_TYPE_NAME", jsonBuilderIndiceSetting);

indices.create(indexRequest).actionGet();

- INDEX_NAME 은 생성한 index

- INDEX_TYPE_NAME 은 생성한 index type

- jsonBuilerIndexSetting 과 jsonBuilderIndiceSetting 은 XContentBuilder 객체

:

elasticsearch 색인 생성 스크립트 예제

Elastic/Elasticsearch 2013. 1. 16. 14:54

그냥 예제 입니다. ㅎㅎ

생성 시 적용된 내용은
- replica 설정
- shards 설정
- refresh interval 설정
- term index interval 설정
- field store 시 compression 설정
- analyzer 설정
- synonym 설정
- routing 설정
- _all disable(?) 설정

# index 삭제

curl -XDELETE 'http://localhost:9200/index0/'


# index 생성

curl -XPUT 'http://localhost:9200/index0' -d '{

    "settings" : {

        "number_of_shards" : 50,

        "number_of_replicas" : 1,

        "index" : {

            "refresh_interval" : "60s",

            "term_index_interval" : "1",

            "store" : {

                "compress" : {

                    "stored" : true,

                    "tv" : true

                }

            },

            "analysis" : {

                "analyzer" : {

                    "kr_analyzer" : {

                        "type" : "custom",

                        "tokenizer" : "kr_tokenizer",

                        "filter" : ["trim", "kr_filter", "kr_synonym"]

                    },

                    "kr_analyzer" : {

                        "type" : "custom",

                        "tokenizer" : "kr_tokenizer",

                        "filter" : ["trim", "kr_filter", "kr_synonym"]

                    }

                },

                "filter" : {

                    "kr_synonym" : {

                        "type" : "synonym",

                        "synonyms_path" : "analysis/synonym.txt"

                    }

                }

            }

        },

        "routing" : {

            "required" : true,

            "path" : "indexType.user_uniq_id"

        }

    },

    "mappings" : {

        "indexType" : {

            "properties" : {

                "docid" : { "type" : "string", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false },

                "rm_seq" : { "type" : "long", "store" : "yes", "index" : "no", "include_in_all" : false },

                "rm_join_seq" : { "type" : "long", "store" : "yes", "index" : "no", "include_in_all" : false },

                "rm_title" : { "type" : "string", "store" : "yes", "index" : "analyzed", "term_vector" : "yes", "analyzer" : "kr_analyzer", "include_in_all" : false },

                "user_uniq_id" : { "type" : "string", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false },

                "mb_nm" : { "type" : "string", "store" : "yes", "index" : "analyzed", "term_vector" : "yes", "analyzer" : "kr_analyzer", "include_in_all" : false },

                "mb_count" : { "type" : "integer", "store" : "yes", "index" : "no", "include_in_all" : false },

                "rm_ymdt" : { "type" : "date", "format" : "yyyyMMddHHmmss", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false },

                "data_size" : { "type" : "long", "store" : "yes", "index" : "no", "include_in_all" : false },

                "msgs" : {

                    "properties" : {

                        "msg_seq" : { "type" : "long", "store" : "no", "index" : "no", "include_in_all" : false },

                        "msg" : { "type" : "string", "store" : "yes", "index" : "analyzed", "term_vector" : "yes", "analyzer" : "kr_analyzer", "include_in_all" : false },

                        "send_user_uniq_id" : { "type" : "string", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false },

                        "send_user_nick_nm" : { "type" : "string", "store" : "yes", "index" : "not_analyzed", "term_vector" : "yes", "analyzer" : "kr_analyzer", "include_in_all" : false },

                        "recv_ymdt" : { "type" : "date", "format" : "yyyyMMddHHmmss", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false },

                        "cfn_yn" : { "type" : "string", "store" : "no", "index" : "no", "include_in_all" : false },

                        "send_yn" : { "type" : "string", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false },

                        "msg_type" : { "type" : "integer", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false }

                    }

                }

            }

        }

    }

}'


: