'Elasticsearch'에 해당되는 글 43건
03. Index APIs - 03 :: 2015/05/19 09:04
Automatic ID Generation
Index operation은 특정 id 지정 없이 실행될 수 있다. 그런 경우에는 id는 자동으로 생성된다. 게다가 op_type은 자동으로 create로 설정될 것이다. 여기에 예제가 있다. (PUT 대신에 POST가 사용되었음에 유의하라.)
$ curl -XPOST 'http://localhost:9200/twitter/tweet/' -d '{
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}'
위의 index operation에 대한 결과는 다음과 같다.
{
"_index" : "twitter",
"_type" : "tweet",
"_id" : "6a8ca01c-7896-48e9-81cc-9f70661fcb32",
"_version" : 1,
"created" : true
}
Routing
기본적으로 shard 위치 - 혹은 routing - 는 document의 id 값을 hash하여 제어된다. 좀 더 명시적인 제어를 위해서 router에 사용된 hash function에 반영된 값은 routing parameter를 사용한 per-operation 기반으로 직접 사용할 수 있다. 예를 들면 다음과 같다.
$ curl -XPOST 'http://localhost:9200/twitter/tweet?routing=kimchy' -d '{
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}'
위의 예제에서 "tweet" document는 제공된 "kimchy" routing parameter에 기반하여 해당 shard로 route된다.
명시적으로 mapping을 설정하면, _routing 필드를 document에서 routing value를 추출하여 index operation에 직접 사용할 수 있다. 이것은 추가적인 document parse측면에서 최소한의 비용으로 처리할 수 있다. 만약 _routing mapping이 정의되고, required로 설정되었을 경우, routing value가 제공되지 않거나 추출한 값이 없으면 index operation은 실패할 것이다.
Parents & Children
Child document는 indexing될 때 parent를 명시하여 index될 수 있다. 예를 들면 다음과 같다.
$ curl -XPUT
localhost:9200/blogs/blog_tag/1122?parent=1111 -d '{
"tag" : "something"
}'
Child document를 indexing할 때, routing value가 routing parameter로 명시적으로 지정되지 않으면, 자동으로 parent와 동일하게 설정된다.
Timestamp
Document는 그와 관련된 timestamp로 index될 수 있다. Document의 timestamp 값은 timestamp parameter를 사용해서 설정할 수 있다. 예를 들면,
$ curl -XPUT
localhost:9200/twitter/tweet/1?timestamp=2009-11-15T14%3A12%3A12 -d '{
"user" : "kimchy",
"message" : "trying out Elasticsearch"
}'
만약 timestamp값이 외부나 _source에 제공되지 않으면, timestamp는 자동으로 document가 index chain에 의해 처리되는 시점의 날짜로 설정될 것이다. 더 많은 정보는 _timestamp mapping page (https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-timestamp-field.html) 에서 찾아볼 수 있다.
02. Index APIs - 02 :: 2015/05/19 08:59
Versioning
각 index된 document는 버전 번호를 갖는다. 이와 연관된 version number는 index API request에 대한 response의 일부분으로 리턴된다. Index API는 선택적으로 version parameter가 명시되면 optimistic concurrency control (낙관적 병행 수행 제어 : RDBMS와 같은 트랜잭션 기반 시스템에 적용되는 concurrency control)을 허용한다. 이것은 operation이 의도와는 반대로 실행되지 않도록 document의 버전을 제어할 것이다. 버전에 대한 훌륭한 use case sample은 transactional read-and-update를 수행하는 것이다. Document의 특정 버전을 명시하면 최초에 읽는 동안 변경되지 않은 데이터를 읽을 수 있다. (업데이트 하기 위해서 데이터를 read하는 경우라면 preference를 _primary로 설정하는 것을 권고한다.) 예를 들면 다음과 같다.
curl -XPUT 'localhost:9200/twitter/tweet/1?version=2' -d '{
"message" : "elasticsearch now has versioning support, double
cool!"
}'
[NOTE]
Versioning은 완전히 real-time (실시간)이다. 그리고 준 실시간 (near real time) 성인 검색 작업에는 영향을 주지 않는다. Version을 제공하지 않을 경우에는 operation은 어떤 버전도 체크하지 않고 실행된다.
기본적으로, 내부적인 versioning은 1부터 시작하여 매 update, delete마다 1씩 증가한다. 선택적으로, version number는 외부 값 (예를 들어, database에 저장된 값)으로 보강될 수 있다. 이런 기능을 가능하게 하기 위해서는 version_type이 external로 설정되어야 한다. Version 값은 0이상 약 9.2e+18 이하의 numeric, long 값이어야만 한다. 매칭되는 version number를 체크하는 대신에 External version type을 사용할 때는 index request로 전달된 version number가 현재 저장된 document의 version 보다 큰지를 알기 위해 시스템에서 체크한다. 만약 더 크면, document는 index되고 새로운 number가 사용될 것이다. 작거나 같으면 version conflict가 발생하고 index operation은 실패할 것이다.
Version number를 database에 저장하도록 하면, async indexing operation에 대한 strict ordering을 유지할 필요가 없다. Database의 데이터를 사용하여 elasticsearch index를 update하는 경우에도 external versioning을 사용하면 단순화할 수 있다. 어떤 이유로든지 index operation이 잘못되더라도 가장 마지막 버전이 사용되기 때문이다.
Version types
위에서 언급된 internal, external version type 다음으로, Elasticsearch는 특정 use case에 대한 다른 type도 지원한다. 다음에서 다른 version type과 의미에 대해서 살펴보자.
internal
주어진 version이 저장된 document의 version과 동일하다면 document를 index한다.
external or external_gt
주어진 version이 저장된 document의 version보다 크거나 현재 존재하는 document가 없으면 document를 index한다. 주어진 version은 새로운 버전으로 사용되고 새로운 document가 저장될 것이다. 적용된 버전은 양수의 long number이어야 한다.
external_gte
주어진 version이 저장된 document의 version 이상일 경우 document를 index한다. Document가 존재하지 않더라도 어쨌거나 operation은 성공할 것이다. 주어진 version은 새로운 version으로 사용되고, 새로운 document와 함께 저장될 것이다. 적용된 버전은 양수의 long number이어야 한다.
force
저장된 document의 version과는 상관없이 document를 index한다. 또는 document가 존재하지 않아도 index한다. 주어진 version은 새로운 version으로 사용되고, 새로운 document와 함께 저장될 것이다. 이 version type은 일반적으로 error를 완전하게 하기 위해서 사용한다.
[NOTE]
external_gte나 force version type은 주의 깊게 사용해야만 하는 특별한 use case를 위해 고안되었다. 부적합하게 사용한다면, 데이터 유실이 발생할 수 있다.
Operation Type
Index operation은 또한 "put-if-absent" 동작을 허용하도록 create operation을 강제화 하는데 사용할 수 있는 op_type을 지원한다. Create가 사용되면, index내에 이미 요청한 id의 document가 존재한다면 index operation은 실패할 것이다.
op_type parameter를 사용하는 예제는 다음과 같다.
$ curl -XPUT 'http://localhost:9200/twitter/tweet/1?op_type=create' -d '{
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}'
또 다른 형태의 예제는 다음과 같다.
$ curl -XPUT 'http://localhost:9200/twitter/tweet/1/_create' -d '{
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}'
01. Index APIs - 01 :: 2015/05/19 08:58
이 섹션에서는 다음 CRUD APIs들을 설명하고 있다.
- Single document APIs
- Index API
- Get API
- Delete API
- Update API
- Multi-document APIs
- Multi Get API
- Bulk API
- Bulk UDP API
- Delete By Query API
[NOTE]
모든 CRUD API는 single-index API이다. Index parameter로는 single index 명이나 single index를 나타내는 alias 명을 사용한다.
Index API
Index API는 특정 index에 검색 가능한 형태로 JSON 형식의 document를 추가하거나 변경하는데 사용한다. 다음 예제는 "twitter" index에 id 1의 "tweet" type으로 JSON document를 추가하는 예제이다.
$ curl -XPUT 'http://localhost:9200/twitter/tweet/1' -d '{
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}'
위의 작업 결과는 다음과 같다.
{
"_index" : "twitter",
"_type" : "tweet",
"_id" : "1",
"_version" : 1,
"created" : true
}
Automatic Index Creation
Index operation은 이전에 index를 생성하지 않았다면 자동으로 생성한다. (수동으로 index를 생성하는 것에 대해서는 create index API - http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html - 를 참고하라.) 그리고 또한, 이전에 만들지 않았다면 자동으로 입력하는 type에 맵핑된 type을 자동으로 생성한다. (type mapping을 수동으로 생성하는 put mapping API - http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html - 를 참고하라.)
Mapping은 그자체로 굉장히 유연하고 schema-free하다. 신규 필드와 object는 특정 type의 mapping definition에 자동으로 추가될 것이다. Mapping definition에 대한 더 자세한 정보를 얻으려면 mapping section을 참고하라.
Index.mapping.allow_type_wrapper를 true로 설정하면, JSON document의 형식은 type (JSON mapper를 사용하면 매우 유용하다) 을 포함할 수 있다.
$ curl -XPOST 'http://localhost:9200/twitter' -d '{
"settings": {
"index": {
"mapping.allow_type_wrapper": true
}
}
}'
{"acknowledged":true}
$ curl -XPUT 'http://localhost:9200/twitter/tweet/1' -d '{
"tweet" : {
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}
}'
Automatic index creation은 모든 node의 config 파일에 있는 action.auto_create_index를 false로 설정하여 사용하지 않도록 할 수 있다. Automatic mapping creation은 모든 node의 config 파일 (또는 특정 index의 설정값) 에 있는 index.mapper.dynamic 값을 false로 설정하여 사용하지 않도록 할 수 있다.
Automatic index creation은 white/black list에 기반한 패턴을 포함하고 있을 수 있다. 예를 들면, action.auto_create_index를 +aaa*, -bbb*, +ccc*, -* 처럼 설정할 수도 있다. (+는 허용, -는 불허를 의미한다.)
12. URL-based Access Control :: 2015/05/13 16:45
많은 사람들이 URL기반으로 Elasticsearch의 index에 접근하기 위한 Access Control을 위해서 Proxy를 사용한다. Multi-search, multi-get, bulk request를 위해서 사용자는 특정 index 정보는 URL에, 각 개별 request 정보는 request body에 담는 것을 선택한다. 이것은 URL 기반 Access Control을 어렵게 한다.
URL에 있는 특정 index를 overrding하는 것을 방지하기 위하여 config.yml 파일에 다음 설정을 추가하라.
rest.action.multi.allow_explicit_index: false
기본값은 true지만, false로 설정했을 때는 Elasticsearch가 request body에 명시된 특정 index가 있다면 request를 reject한다.
11. Common Options - 02 :: 2015/05/13 16:45
Distance Units
거리가 필요할 경우, 예를 들어 Geo Distance Filter의 distance parameter와 같은 경우에 아무것도 단위가 명시되어 있지 않을 경우에는 기본적으로 미터단위이다. "1km"나 "2mi" (miles)와 같이 다른 단위로도 distance를 명시할 수 있다. 전체 리스트는 다음과 같다.
mi or miles : Mile
yd or yards : Yard
ft or feet : Feet
in or inch : Inch
km or kilometers : Kilometer
m or meters : Meter
cm or centimeters : Centimeter
mm or millimeters : Millimeter
NM, nmi or nauticalmiles : Nautical Mile
Geohash Cell Filter의 precision (정밀도) parameter는 위에 명시된 unit으로 거리를 표시한다. 하지만, unit이 명시되지 않았을 경우에는 geohash의 길이로 precision을 해석한다.
Fuzziness
어떤 query나 API는 fuzziness parameter를 사용하여 부정확한 fuzzy matching을 지원한다. Fuzziness parameter는 query에 사용된 field의 type에 따른 context에 따른다.
Numeric, date and IPv4 fields
숫자나 날짜, IPv4 field가 query에 있을 때, fuzziness는 +/- margin으로 해석한다. 마치 다음과 같은 Range Query처럼 동작한다.
-fuzziness <= field value <= +fuzziness
Fuzziness parameter는 2나 2.0처럼 숫자로 표시되어야 한다. Date field는 밀리초단위의 long값으로 해석된다. 하지만, 시간 단위를 가진 string값 - "1h"와 같은 - 은 단위에서 의미하는 값으로 받아들인다. Ip field는 long이나 또 다른 IPv4 주소 (long으로 변환될 수 있는) 를 수용한다.
String fields
Query에 string이 사용되었을 경우, fuzziness는 Levenshtein Edit Distance (http://en.wikipedia.org/wiki/Levenshtein_distance) - 하나의 문자가 숫자로 변경되는 - 로 처리된다.
Fuzziness parameter는 다음과 같이 정리할 수 있다.
0, 1, 2 : Levenshtein Edit Distance에 허용되는 최대값
AUTO : 길이에 따라 edit distance를 계산함.
0..1 : 정확히 일치하는 경우
1..5 : one edit만 허용
>5 : two edit 허용
AUTO는 fuzziness에 대한 최적값을 계산한다.
0.1..1.0 : 공식을 통해서 edit distance를 계산한다. Length(term) * (1.0 - fuzziness). 예를 들어 길이 10을 가진 fuzziness가 0.6이면 edit distance는 10 * (1.0 - 0.6) = 4.0이다.
[NOTE]
모든 API에 대한 Fuzzy Like This Query (http://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-flt-query.html) 측면에서 edit distance의 최대값은 2이다.
Result Casing
모든 REST API는 case parameter를 가질 수 있다. camelCase가 설정될 때는 결과에 속한 모든 field name에 camel casing이 있는 결과를 리턴할 것이다. 아니면 underscore가 사용된 결과가 리턴될 것이다. Index된 source document에는 적용되지 않는다.
JSONP
사용가능할 때, 모든 REST API는 JSONP 결과 내, callback parameter 결과를 받을 수 있다. Config.yaml 파일에 다음 항목을 추가함으로 수행 가능하다.
http.jsonp.enable:true
사용가능하도록 설정되었을 때, elasticsearch의 아키텍처 때문에 security risk를 야기한다는 것에 주의하라. 특정 환경하에서는 attacker가 여러분의 브라우저를 이용해 JSONP request를 만들어서 Elasticsearch Server의 데이터를 탈취할 수 있다.
Request body in query string
POST가 아닌 request에 대해서 body를 수용하지 않는 library에 대해서 string parameter의 source query를 이용해 body를 전송할 수 있다.