|
Elastic/Elasticsearch 2013. 4. 17. 11:32
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch API 리뷰] 원문 링크 : http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping/
이 API 는 Mapping type 을 정의 할 수 있도록 합니다.
[Merging & Conflicts] - 이미 존재 하는 field 에 다른 type 으로 mapping 시도 시 merge & conflict 동작을 하게 됩니다. - ignore_conflicts 설정을 true 로 할 경우 다른 type 에 대한 conflict 에러를 회피 할 수 있습니다. - 하지만, 정상적인 동작은 하지 않는다는 점에 주의를 하셔야 합니다. kimchy said : You can't change the type of a field mapped, even when ignore_conflicts is set to true. Ignore conflicts simply does that, ignore the conflicts and applies what it can, it does not apply conflicts.
※ 정리 하면, - 기정의한 field type 에 대한 변경을 하지 않도록 유의 합니다. - 만약 변경이 필요 하다면, object type 으로 신규 추가 하거나 multi field 를 활용 하시기 바랍니다.
Elastic/Elasticsearch 2013. 4. 17. 10:26
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch API 리뷰] 원문 링크 : http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases/
[Indices Aliases] 이 API 는 index name 의 별칭을 생성 및 삭제를 할 수 있도록 한다. 하나의 별칭에 여러개의 index name 을 등록 할 수도 있으며 filter 를 통해 같은 index 의 또 다른 view 를 구현 할 수 있다. 관련 예제는 원문에 잘 나와 있기 때문에 Java API 샘플 코드만 살펴 보도록 한다.
[샘플코드 : IndicesAliasesRequestBuilder.java] clientManager.openClient(); // singletone 객체를 이용한 connection manager
Client client = clientManager.getClient();
AdminClient admin = client.admin();
ClusterAdminClient cluster = admin.cluster();
IndicesAdminClient indices = admin.indices();
IndicesAliasesRequestBuilder aliases = new IndicesAliasesRequestBuilder(indices);
IndicesAliasesResponse response = aliases.addAlias("blog", "aliases_blog2")
.removeAlias("blog", "aliases_blog1")
.execute()
.actionGet();
log.debug("{}", response); // slf4j logger
[Filtered Aliases] curl -XPOST 'http://localhost:9200/_aliases' -d '
{
"actions" : [
{
"add" : {
"index" : "test1",
"alias" : "alias2",
"filter" : { "term" : { "user" : "kimchy" } }
}
}
] }'
- 이미 위에서 언급 했듯이 RDBMS 에서 사용하는 view table 과 비슷한 목적으로 사용이 가능 하다고 이해 하면 쉽다.
Elastic/Elasticsearch 2013. 4. 16. 22:13
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch API 리뷰] 원문 링크 : http://www.elasticsearch.org/guide/reference/api/more-like-this/
이 기능은 like 검색과 같은 기능을 제공해 줍니다. 단, match 단위는 term 이라는 점에 유의 하셔야 합니다. 좀더 상세한 내용은 아래 링크를 참고 하시기 바라며, 관련 코드는 MoreLikeThisQueryBuilder.java 를 보시기 바랍니다.
[More Like This 상세] http://www.elasticsearch.org/guide/reference/query-dsl/mlt-query/
Elastic/Elasticsearch 2013. 4. 16. 18:43
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch API 리뷰] 원문 링크 : http://www.elasticsearch.org/guide/reference/api/search/
[Filter] - http://www.elasticsearch.org/guide/reference/api/search/filter/ - 실행한 query 결과를 바탕으로 filtering 할 수 있는 옵션
[Rescore] - http://www.elasticsearch.org/guide/reference/api/search/rescore/ - search_type 이 scan 또는 count 일 경우 실행 되지 않음 - query 와 filter 를 통해서 결과를 return 함.
[Highlight] - http://www.elasticsearch.org/guide/reference/api/search/highlighting.html - store : yes 와 term_vector : with_positions_offsets 설정이 되어 있어야 함. - query 생성 시 아래와 같은 속성으로 설정 highlight .pre_tags .post_tags .tags_schema .fields
[Highlighted Fragments] {
"query" : {...},
"highlight" : {
"order" : "score",
"fields" : {
"content" : {"fragment_size" : 150, "number_of_fragments" : 3}
}
} }
{
"query" : {...},
"highlight" : {
"fields" : {
"_all" : {},
"bio.title" : {"number_of_fragments" : 0}
}
}
} - highlight character size = fragment_size (기본 100) - highlight size = number_of_fragments (기본 5) - number_of_fragments=0 이면 highlight 된 전체 내용을 return 함. - boundary characters 는 . boundary_chars 와 boundary_max_scan 속성을 갖는다.
[Fields] - http://www.elasticsearch.org/guide/reference/api/search/fields.html - 검색 결과에 화면에 보여주기 위한 field 를 정의 함 - 기본 store : yes 설정이 되어야 하면 no 라면 _source 값을 load 하게 됨.
[Script Fields] - http://www.elasticsearch.org/guide/reference/api/search/script-fields/ - http://www.elasticsearch.org/guide/reference/modules/scripting/ - 쿼리 결과에 대한 별도의 연산 작업을 통해 지정한 field 명으로 연산된 값을 return 한다. { "query" : {
...
},
"script_fields" : {
"test1" : {
"script" : "doc['my_field_name'].value * 2"
},
"test2" : {
"script" : "doc['my_field_name'].value * factor",
"params" : {
"factor" : 2.0
}
}
} }
Its important to understand the difference between doc['my_field'].value and _source.my_field.
[Preference] - http://www.elasticsearch.org/guide/reference/api/search/preference/ - 검색 요청 시 shard control 을 통해서 사용
[Term Facet] - http://www.elasticsearch.org/guide/reference/api/search/facets/terms-facet/ {
"query" : {
"match_all" : { }
},
"facets" : {
"tag" : {
"terms" : {
"field" : "tag",
"size" : 10,
"order" : "term"
}
}
} }
- tag field 에서 가장 빈번한 term(size) 10 개, ordering 은 term 으로 수행. - ordering option 은 count, term, reverse_count, reverse_term (기본 count)
[Range Facet] - http://www.elasticsearch.org/guide/reference/api/search/facets/range-facet/ - range facet 을 사용하기 위해서는 IndexNumericFieldData(RangeFacetExecutor.java) 를 가져야 함.
- key and value 에서는 key 는 range 비교 항목으로 사용하고, value 는 비교된 결과에 aggregate 연산(total)을 함 - script key and value 사용 가능 함 {
"query" : {
"match_all" : {}
},
"facets" : {
"range1" : {
"range" : {
"key_script" : "doc['date'].date.minuteOfHour",
"value_script" : "doc['num1'].value",
"ranges" : [
{ "to" : 50 },
{ "from" : 20, "to" : 70 },
{ "from" : 70, "to" : 120 },
{ "from" : 150 }
]
}
}
} }
[Statistical Facet] Statistical facet allows to compute statistical data on a numeric fields. The statistical data include count, total, sum of squares, mean (average), minimum, maximum, variance, and standard deviation.
- numeric fields 에 대해서 통계적 데이터를 계산함. - script field 와 multi field 지원 함.
[Term Stats Facet] - term 과 statistical 조합 - size 속성의 기본 값은 10 - size 가 0 인 경우 전체 matching term 을 return 한다. (주의, 너무 많은 결과가 나올 수 있음) - ordering 옵션은 아래와 같다. term, reverse_term, count, reverse_count, total, reverse_total, min, reverse_min, max, reverse_max, mean, reverse_mean. Defaults to count.
Elastic/Elasticsearch 2013. 4. 16. 15:22
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch 리뷰] 원문 링크 http://www.elasticsearch.org/guide/reference/api/get.html http://www.elasticsearch.org/guide/reference/api/multi-get.html http://www.elasticsearch.org/guide/reference/api/update.html
위 3개의 API 들은 Java API 를 참고하는게 더 좋습니다. 기본 Core API 에서 보여 주고 있는 예제는 REST API 로 kimchy 가 추천하는 방식과는 조금 다른 예제로 보여 주기 위한 목적이 강하다는 판단 입니다.
kimchy 의 추천은 Native Java API 를 사용할 것을 추천 합니다.
Elastic/Elasticsearch 2013. 4. 16. 15:03
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch 리뷰] 원문 링크 : http://www.elasticsearch.org/guide/reference/api/delete/
Parent - routing 설정과 동일하게 동작 함
Replication Type - 기본 sync 로 동작 하면 async 설정 가능 함 - async 설정 시 primary shard 만 적용 되면 성공
Elastic/Elasticsearch 2013. 4. 16. 12:04
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch 리뷰] 원문 링크 http://www.elasticsearch.org/guide/reference/mapping/ http://www.elasticsearch.org/guide/reference/mapping/array-type/ http://www.elasticsearch.org/guide/reference/mapping/object-type/ http://www.elasticsearch.org/guide/reference/mapping/nested-type/
원문 예제가 잘 나와 있어 그대로 사용 합니다.
[Document] "tweet" : {
"message" : "some arrays in this tweet...",
"tags" : ["elasticsearch", "wow"],
"lists" : [
{
"name" : "prog_list",
"description" : "programming list"
},
{
"name" : "cool_list",
"description" : "cool stuff list"
}
]
}
[Mapping] "tweet" : {
"properties" : {
"message" : {"type" : "string"},
"tags" : {"type" : "string", "index_name" : "tag"},
"lists" : {
"properties" : {
"name" : {"type" : "string"},
"description" : {"type" : "string"}
}
}
}
}
[설명] - elasticsearch 가 지원 하는 장점 중 하나 입니다. - mapping 정보를 보면 문서 안에 sub 문서를 만들어 넣을 수 있습니다. - _parent field 의 경우 index type 에 대한 parent 구조를 만들 수 있다고 하면 이건 document 자체에 parent-child 구조를 만들수 있습니다. - mapping 에서 사용하는 index_name 의 경우 이런 array type 에 대해서 색인 시 field 명을 정의 할 수가 있습니다. - nested loop 구조를 요구하는 문서가 있을 경우 잘 활용 하시면 좋습니다. - 예를 들면 대화방이 있고 대화방안에는 여러 사람들이 나눈 대화 목록이있을 경우 "chat_room" : { "properties" : { "room_id" : {.....}, ........ "chat_lists" : { "properties" : { "chat_id" : {....}, "sender" : {....}, "receiver" : {....}, "message" : {....) } } } } . 이와 같은 구조로 생성을 할 수도 있습니다.
[Object/Nested] - 이 두가지 type 도 array 와 유사 합니다. - array 의 경우 [] 이와 같이 사용했다면, object 는 {} 을 사용하게 됩니다. - nested 타입은 정의한 field 형식의 집합을 구성하게 됩니다. object 로 정의한 형식이 있다면 이것을 여러개의 집합으로 구성을 하게 됩니다. 아래 원문에 나온 예제를 보시면 쉽게 이해가 됩니다.
[Object 예제] "person" : {
"properties" : {
"name1" : {
"type" : "object",
"path" : "just_name",
"properties" : {
"first1" : {"type" : "string"},
"last1" : {"type" : "string", "index_name" : "i_last_1"}
}
},
"name2" : {
"type" : "object",
"path" : "full",
"properties" : {
"first2" : {"type" : "string"},
"last2" : {"type" : "string", "index_name" : "i_last_2"}
}
}
}
}
- path 는 두가지 옵션을 갖습니다. . just_name 과 full . just_name 의 경우 mapping 에서 정의한 index_name 을 사용하게 되며 . full 의 경우 mapping 에서 정의한 full name 을 사용하게 됩니다. - 즉 원문에 나온 결과를 보시면 이해가 쉽습니다. JSON Name | Document Field Name |
---|
name1 /first1 | first1 | name1 /last1 | i_last_1 | name2 /first2 | name2.first2 | name2 /last2 | name2.i_last_2 |
[Nested 예제] {
"type1" : {
"properties" : {
"obj1" : {
"type" : "nested"
}
}
}
} - 위 예제에서는 "obj1" 내부 field 정의가 빠져 있으나 설정이 가능 합니다. - 아래와 같이 하시면 됩니다.
"obj1" : { "type" : "nested", "properties" : { "first_name" : { "type" : "string", ....}, "last_name" : { "type" : "string", ....} ...... } }
Elastic/Elasticsearch 2013. 4. 16. 10:57
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch java api 리뷰] 원문 링크 http://www.elasticsearch.org/guide/reference/mapping/
이번 문서는 Java API에서도 제공하고 있는 mapping 관련 설정 값들 입니다. 자세한 설명은 원문의 Fields 와 Types 부분은 꼭 한번 씩 보시기 바랍니다.
[Mapping Template Sample] "mapping" : { "TYPE_NAME" : { "analyzer" : "standard", "index_analyzer" : "stadnard", "search_analyzer" : "standard", "_id" : { "index" : "not_analyzed", "store" : "yes", "path" : "FIELD_NAME" }, "_type" : { "index" : "not_analyzed", "store" : "yes" }, "_source" : { "enabled" : "false" }, "_all" : { "enabled" : "false" }, "_boost" : { "name" : "_boost", "null_value" : 1.0 }, "_parent" : { "type" : "PARENT_TYPE_NAME" }, "_routing" : { "required" : true, "path" : "TYPE_NAME.FIELD_NAME" }, "_timestamp" : { "enabled" : true, "path" : "DATE_FIELD_NAME", "format" : "dateOptionalTime" }, "properties" : { "FIELD_NAME" : { "type" : "string", "index_name" : , "store" : , "index" : , "term_vector" : , "boost" : , "null_value" : , "omit_norms" : , "omit_term_freq_and_positions" : , "index_options" : , "analyzer" : , "index_analyzer" : , "search_analyzer" : , "include_in_all" : , "ignore_above" : , "position_offset_gap" : }, "FIELD_NAME" : { "type" : "float, double, byte, short, integer, and long", "index_name" : , "store" : , "index" : , "precision_step" : , "null_value" : , "boost" : , "include_in_all" : , "ignore_malformed" : }, "FIELD_NAME" : { "type" : "date", "index_name" : , "format" : , "store" : , "index" : , "precision_step" : , "null_value" : , "boost" : , "include_in_all" : , "ignore_malformed" : }, "FIELD_NAME" : { "type" : "boolean", "index_name" : , "store" : , "index" : , "null_value" : , "boost" : , "include_in_all" : , }, "FIELD_NAME" : { "type" : "binary", "index_name" : , } } } }
[Fields & Core Type] fields _id document 의 unique id 는 _uid (_id + _type) 이며, _id 는 색인 ID 로 사용될 수 있다. 기본적으로 색인되지 않고 저장 하지 않습니다. _type 기본적으로 색인은 하지만 저장은 하지 않습니다. _source 자동으로 field 생성을 허용할지 결정 합니다. _all 하나 또는 더 많은 field 를 색인시 저장 할 것인지 결정을 합니다. "simple1" : {"type" : "long", "include_in_all" : true}, "simple2" : {"type" : "long", "include_in_all" : false} _analyzer (설정 하지 않아도 되는 field) 색인 시 등록된 analyzer 또는 index_analyzer 를 사용 합니다. 또한, 특정 field 를 지정 할 경우 해당 field 에 정의된 analyzer 를 사용하게 됩니다. _boost 문서나 field 의 연관성을 향상시키기 위해 사용한다. _parent parent type 을 지시하는 child mapping 정의 입니다. blog type 과 blog_tag type 이 있을 경우 blog_tag 의 parent type 은 blog 가 됩니다. _routing 색인 데이터에 대한 routing 관리를 위해서 사용 합니다. routing field 는 store : yes, index : not_analyzed 로 설정이 되어야 합니다. _index (설정 하지 않아도 되는 field) index 가 소유한 문서를 store 합니다. default false 로 저장 하지 않음. _size (설정 하지 않아도 되는 field) _source 에 의해서 자동으로 생성된 색인 field 의 수. default disabled 입니다. _timestamp 색인 시 문서의 timestamp 입니다. 기본 store : no, index : not_analyzed 이며, 설정 시 field 지정이 가능 합니다. format 은 기본 dateOptionalTime. (http://www.elasticsearch.org/guide/reference/mapping/date-format/) _ttl 색인 시 문서의 expiration date를 설정 합니다. 기본 disabled 입니다. 설정 시 ttl 이후 문서는 자동 삭제 됩니다. core types string type index_name array type 선언 시 사용되는 항목으로 array list 항목에 대한 개별 field 명으로 사용된다. store default no 이며, 저장에 대한 설정을 위해서 사용 된다. yes 시 저장 index 검색 또는 색인 시 분석관련 설정을 위해서 사용 된다. analyzed 검색과 색인 시 analyzer 를 이용해서 분석 not_analyzed 검색가능 하다는 의미 no 검색 불가능 하다는 의미 term_vector 기본 no 설정 no yes with_offsets with_positions with_positions_offsets boost 기본 1.0 null_value null value 시 기본 값은 아무것도 넣지 않으나 설정한 값이 있을 경우 등록 함. omit_norms 기본 false 로 analyzed field 설정, true 일 경우 not_analyzed field 에서 설정 index_options 색인 옵션 docs not_analyzed field freqs analyzed field positions analyzed field analyzer global 설정으로 검색과 색인 시 사용된다. index_analyzer 색인 시에 사용된다. search_analyzer 검색 시에 사용된다. include_in_all 기본 true 로 설정 됨. _all field 에 저장할 것인지 지정함. ignore_above 지정한 크기 이상의 문자열을 무시 합니다. position_offset_gap number type type : "float, double, byte, short, integer, and long", index_name store index precision_step number 의 term value 를 만들어 냅니다. 설정 값이 작을 수록 검색은 빠르게 이루어 집니다. 기본 값은 4이며, 32bits 는 4 정도, 64bits 는 6~8정도를 사용합니다. 0 은 disable 입니다. null_value boost include_in_all ignore_malformed 비정상적인 숫자를 무시 한다. 기본 false로 설정 되어 있기 때문에 true 설정 하는 것이 좋다. date type index_name format http://www.elasticsearch.org/guide/reference/mapping/date-format.html store index precision_step number 의 term value 를 만들어 냅니다. 설정 값이 작을 수록 검색은 빠르게 이루어 집니다. 기본 값은 4이며, 32bits 는 4 정도, 64bits 는 6~8정도를 사용합니다. 0 은 disable 입니다. null_value boost include_in_all ignore_malformed 비정상적인 숫자를 무시 한다. 기본 false로 설정 되어 있기 때문에 true 설정 하는 것이 좋다. boolean type index_name store index null_value boost include_in_all binary type index_name
Elastic/Elasticsearch 2013. 4. 16. 10:54
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch java api 리뷰] 원문 링크 http://www.elasticsearch.org/guide/reference/modules/ http://www.elasticsearch.org/guide/reference/index-modules/ http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings/
이번 문서는 Java API에서도 제공하고 있는 settings 관련 설정 값들 입니다.
물론 cluster.settings 와 index.settings 도 있기 때문에 모두 확인을 하셔야 합니다. 보통 cluster 와 index 에 대한 설정들은 모두 global setting 을 사용하도록 구성 하기 때문에 elasticsearch.yml 을 구성 할 때 활용 하시면 됩니다.
업데이트 세팅과 작성된 JSON 형식의 예제를 확인해 보도록 하겠습니다.
[admin indices update settings] Setting | Description |
---|
index.number_of_replicas | The number of replicas each shard has. | index.auto_expand_replicas | Set to an actual value (like 0-all ) or false to disable it. | index.blocks.read_only | Set to true to have the index read only. false to allow writes and metadata changes. | index.blocks.read | Set to true to disable read operations against the index. | index.blocks.write | Set to true to disable write operations against the index. | index.blocks.metadata | Set to true to disable metadata operations against the index. | index.refresh_interval | The async refresh interval of a shard. | index.term_index_interval | The Lucene index term interval. Only applies to newly created docs. | index.term_index_divisor | The Lucene reader term index divisor. | index.translog.flush_threshold_ops | When to flush based on operations. | index.translog.flush_threshold_size | When to flush based on translog (bytes) size. | index.translog.flush_threshold_period | When to flush based on a period of not flushing. | index.translog.disable_flush | Disables flushing. Note, should be set for a short interval and then enabled. | index.cache.filter.max_size | The maximum size of filter cache (per segment in shard). Set to -1 to disable. | index.cache.filter.expire | The expire after access time for filter cache. Set to -1 to disable. | index.gateway.snapshot_interval | The gateway snapshot interval (only applies to shared gateways). | merge policy | All the settings for the merge policy currently configured. A different merge policy can’t be set. | index.routing.allocation.include.* | A node matching any rule will be allowed to host shards from the index. | index.routing.allocation.exclude.* | A node matching any rule will NOT be allowed to host shards from the index. | index.routing.allocation.require.* | Only nodes matching all rules will be allowed to host shards from the index. | index.routing.allocation.total_shards_per_node | Controls the total number of shards allowed to be allocated on a single node. Defaults to unbounded. | index.recovery.initial_shards | When using local gateway a particular shard is recovered only if there can be allocated quorum shards in the cluster. It can be set to quorum (default), quorum-1 (or half ), full and full-1 . Number values are also supported, e.g. 1 . | index.gc_deletes | | index.ttl.disable_purge | Disables temporarily the purge of expired docs. |
이 세팅 값들은 서비스 특성에 맞게 구성을 하셔야 합니다. 아래는 위 속성들에 대한 참고용 입니다.
[Sample JSON String] curl -XPUT 'http://localhost:9200/test/' -d '{ "settings" : { "number_of_shards" : 5, "number_of_replicas" : 1, "index" : { "analysis" : { "analyzer" : { "default" : { "type" : "standard", "tokenizer" : "standard", "filter" : ["lowercase", "trim"] }, "default_index" : { "type" : "standard", "tokenizer" : "standard", "filter" : ["lowercase", "trim"] }, "default_search" : { "type" : "standard", "tokenizer" : "standard", "filter" : ["lowercase", "trim"] }, "my_analyzer1" : { "tokenizer" : "standard", "filter" : ["standard", "lowercase", "trim"] }, "my_analyzer2" : { "type" : "custom", "tokenizer" : "tokenizer1", "filter" : ["filter1", "trim"] } }, "tokenizer" : { "tokenizer1" : { "type" : "standard", "max_token_length" : 255 } }, "filter" : { "filter1" : { "type" : "lowercase", "language" : "greek" } } }, "compound_format" : false, "merge" : { "policy" : { "max_merge_at_once" : 10, "segments_per_tier" : 20 } }, "refresh_interval" : "1s", "term_index_interval" : 1, "store" : { "type" : "mmapfs", "compress" : { "stored" : true, "tv" : true } } } } }'
- 위 표에 없는 설정에 대해서만 기술 합니다.
number_of_shards |
색인 파일에 대한 shard 수 |
index.analysis.analyzer .default .default_index .default_search .my_analyzer1 .my_analyzer2 .tokenizer .filter |
색인 및 검색 시 사용할 분석기를 등록함 .default* 은 기본 분석기를 등록 index/type 에 대한 기본 설정으로 동작 .my_analyzer* 은 사용자 정의 분석기 .tokenizer 와 .filter 는 analyzer 에서 사용하게 될 tokenizer 와 filter 를 정의 |
index.compound_format |
파일 기반 저장 시스템을 사용할 경우 false 로 설정해야 더 나은 성능을 지원함 |
index.store.type |
|
index.store.compress .stored .tv |
색인 저장 시 압축 기능에 대한 설정 . 64KB 이하의 작은 문서에 대한 압축 효과가 좋음 |
Elastic/Elasticsearch 2013. 4. 15. 11:36
본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며, 정보 교환이 목적입니다.
잘못된 부분에 대해서는 지적 부탁 드립니다. (예시 코드는 성능 및 보안 검증이 되지 않았습니다.)
[elasticsearch java api 리뷰] 원문 링크 : http://www.elasticsearch.org/guide/reference/java-api/search/
- 이 API는 검색 쿼리를 실행 할 수 있으며, 쿼리와 일치하는 결과를 구할 수 있습니다.
원문 예제 부터 살펴 보겠습니다. SearchResponse response = client.prepareSearch("index1", "index2") .setTypes("type1", "type2") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(QueryBuilders.termQuery("multi", "test")) // Query .setFilter(FilterBuilders.rangeFilter("age").from(12).to(18)) // Filter .setFrom(0).setSize(60).setExplain(true) .execute() .actionGet();
- 두 개의 색인 파일에 대한 검색 조건을 생성 합니다. (index1 과 index2) - 역시 각 index 에 대한 type을 지정 합니다. - REST 방식으로 표현하게 되면 http://localhost:9200/index1,inde2/type1,type2/_search?....... 과 같이 됩니다. - http://www.elasticsearch.org/guide/reference/api/search/indices-types/ - termQuery 에서 multi 라는 field 에 test 라는 term 을 찾게 됩니다.
/**
* A Query that matches documents containing a term.
*
* @param name The name of the field
* @param value The value of the term
*/
public static TermQueryBuilder termQuery(String name, String value) {
return new TermQueryBuilder(name, value);
}
[Operation Threading Model] - NO_THREADS : 호출된 쓰레드에서 실행 - SINGLE_THREAD : 또 다른 하나의 쓰레드를 생성하여 모든 shard 를 조회 - THREAD_PER_SHARD : 각 개별 shard 별로 쓰레드를 생성하여 실행 - Default SINGLE_THREAD 로 설정이 되어 있고, 성능적인 확인은 필요함.
[MultiSearch API] SearchRequestBuilder srb1 = node.client() .prepareSearch().setQuery(QueryBuilders.queryString("elasticsearch")).setSize(1); SearchRequestBuilder srb2 = node.client() .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);
MultiSearchResponse sr = node.client().prepareMultiSearch() .add(srb1) .add(srb2) .execute().actionGet();
// You will get all individual responses from MultiSearchResponse#responses() long nbHits = 0; for (MultiSearchResponse.Item item : sr.responses()) { SearchResponse response = item.response(); nbHits += response.hits().totalHits(); }
- 개별 검색 조건에 대한 한번의 요청으로 각각의 검색 결과를 얻을 수 있습니다.
[Using Facets] - http://www.elasticsearch.org/guide/reference/java-api/facets/ SearchResponse sr = node.client().prepareSearch() .setQuery(QueryBuilders.matchAllQuery()) .addFacet(FacetBuilders.termsFacet("f1").field("field")) .addFacet(FacetBuilders.dateHistogramFacet("f2").field("birth").interval("year")) .execute().actionGet();
// Get your facet results TermsFacet f1 = (TermsFacet) sr.facets().facetsAsMap().get("f1"); DateHistogramFacet f2 = (DateHistogramFacet) sr.facets().facetsAsMap().get("f2"); - facet 검색은 검색 결과에 대한 분류 또는 그룹핑으로 이해 하시면 접근 하시는데 조금 쉽습니다. - termsFacet("f1") 에서 f1 은 facet name 입니다.
아래 부터는 테스트로 작성한 코드 입니다. 참고용으로만 사용하시기 바랍니다.
[기본 Query Search]
response = client.prepareSearch("facebook")
.setOperationThreading(SearchOperationThreading.THREAD_PER_SHARD)
.setRouting("1365503894967")
.setTypes("post")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("title", "9"))
.setFrom(0)
.setSize(20)
.setExplain(true)
.execute()
.actionGet();
log.debug("{}", response);
[Multi Search] SearchRequestBuilder srb1 = client
.prepareSearch("facebook").setQuery(QueryBuilders.queryString("93").field("title")).setSize(1);
SearchRequestBuilder srb2 = client
.prepareSearch("facebook").setQuery(QueryBuilders.matchQuery("title", "94")).setSize(1);
MultiSearchResponse sr = client.prepareMultiSearch()
.add(srb1)
.add(srb2)
.execute().actionGet();
// You will get all individual responses from MultiSearchResponse#responses()
long nbHits = 0;
for (MultiSearchResponse.Item item : sr.responses()) {
response = item.response();
log.debug("{}", response);
}
[MatchQeury]
response = client.prepareSearch("facebook")
.setOperationThreading(SearchOperationThreading.THREAD_PER_SHARD)
.setTypes("post")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(
QueryBuilders.matchQuery("title", "1365577624100 twitter")
.type(Type.BOOLEAN) // default, PHASE 와 PHARE_PREFIX 는 하나의 TERM 으로 매칭.
.analyzer("gruter_analyzer") // analyzer는 지정 하지 않으면 settings 값으로 동작 함.
.operator(Operator.OR) // query 에 대한 token 연산을 의미 함.
)
.setFrom(0)
.setSize(5)
.setExplain(false)
.execute()
.actionGet();
log.debug("{}", response);
[Multi MatchQuery] response = client.prepareSearch("facebook")
.setOperationThreading(SearchOperationThreading.THREAD_PER_SHARD)
.setTypes("post")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(
QueryBuilders.multiMatchQuery("136557762410", "docid", "title") // 각 field 에 대해서 matchQuery 를 수행 하는 것과 같은 효과.
.type(Type.PHRASE_PREFIX)
.operator(Operator.OR)
)
.setFrom(0)
.setSize(14)
.setExplain(false)
.execute()
.actionGet();
log.debug("{}", response);
[Facet Search]
response = client.prepareSearch("blog")
.setQuery(QueryBuilders.matchAllQuery())
.addFacet(FacetBuilders.termsFacet("facetYear").field("year"))
.addFacet(FacetBuilders.termsFacet("facetMonth").field("month"))
.addFacet(FacetBuilders.termsFacet("facetDay").field("day"))
.execute()
.actionGet();
TermsFacet facetYear = (TermsFacet) response.facets().facetsAsMap().get("facetYear");
TermsFacet facetMonth = (TermsFacet) response.facets().facetsAsMap().get("facetMonth");
TermsFacet facetDay = (TermsFacet) response.facets().facetsAsMap().get("facetDay");
log.debug("{}", response);
- facet search 테스트를 위한 scheme 정보는 아래와 같습니다. "mappings" : { "post" : { "properties" : { "docid" : { "type" : "string", "store" : "yes", "index" : "not_analyzed", "include_in_all" : false }, "title" : { "type" : "string", "store" : "yes", "index" : "analyzed", "term_vector" : "yes", "analyzer" : "gruter_analyzer", "include_in_all" : false }, "year" : { "type" : "integer", "store" : "no", "index" : "not_analyzed", "include_in_all" : false }, "month" : { "type" : "integer", "store" : "no", "index" : "not_analyzed", "include_in_all" : false }, "day" : { "type" : "integer", "store" : "no", "index" : "not_analyzed", "include_in_all" : false } } } }
|