'Index API'에 해당되는 글 4건
04. Index APIs - 04 :: 2015/05/19 09:05
TTL
Document는 그와 관련된 ttl (Time To Live) 값을 가지고 index될 수 있다. 폐기된 document는 자동으로 삭제된다. Ttl값으로 제공되는 document의 폐기 일자는 document의 index되는 시점이나 값으로 제공되는 어느 특정 시간의 timestamp와 관련되어 있다. 값으로 제공되는 ttl값은 양수값이어야만 하고, milliseconds 단위의 숫자나 다음 예제에서 보여지는 적합한 시간 값이어야 한다.
curl -XPUT 'http://localhost:9200/twitter/tweet/1?ttl=86400000' -d '{
"user": "kimchy",
"message": "Trying out elasticsearch, so far
so good?"
}'
curl -XPUT 'http://localhost:9200/twitter/tweet/1?ttl=1d' -d '{
"user": "kimchy",
"message": "Trying out elasticsearch, so far
so good?"
}'
curl -XPUT 'http://localhost:9200/twitter/tweet/1' -d '{
"_ttl": "1d",
"user": "kimchy",
"message": "Trying out elasticsearch, so far
so good?"
}'
더 많은 정보는 _ttl mappling page (https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-ttl-field.html) 에서 찾아볼 수 있다.
Distributed
Index operation은 위 routing section에서 본 것처럼 직접적으로 primary shard 기반 route하고, shard가 있는 실제 노드에서 수행된다. Primary shard에서 operation이 완료되면, 필요한 경우에, 업데이트는 replica에 분산처리 된다.
Write Consistency
잘못된 network side에 write하는 것을 방지하기 위해서, 기본적으로 index operation은 active shard의 수가 quorum (replicas의 2분의 1 + 1)일 때 성공적으로 수행된다. 이 기본값은 action.write_consistency 설정을 통해서 node-by-node별로 덮어쓸 수 있다. Operation별로 consistency parameter로 보내면 이 값을 변경시킬 수 있다.
유효한 write consistency 값으로는 one, quorum, all이 있다.
Replica의 숫자가 1인 경우 (전체 데이터 복제본이 2개) 에는 기본 동작은 1개의 copy (primary)에서 write가 발생하면, 성공한다.
Asynchronous Replication
[WARNING]
1.5.0에서 삭제되었음. Asynch replication을 지정하는 것은 deprecated (더 이상 사용되지 않고 앞으로 사라질 것으로 마크) 되었고, 2.0.0에서는 삭제될 것이다.
기본적으로 index operation은 replication group에 있는 모든 shard가 document를 index하고 나서 리턴한다. (sync replication임). Asynchronous replication을 사용하기 위해서는 background로 replication process가 일어나기 때문에 replication parameter를 async로 설정해야 한다. Asynchronous replication이 사용될 때, index operation은 primary shard에 성공적으로 operation이 수행되었을 경우에 바로 결과를 리턴할 것이다.
Replication 설정의 기본 값은 sync이다. 그리고 이 기본 값은 action.replication_type 설정을 사용하여 노드별 기본 설정값으로 덮어쓸 수 있다. Replication type의 유효한 값으로는, sync와 async가 있다. Operatio별로 이 동작을 다르게 하기 위해서는 replication request parameter를 이용할 수 있다.
Refresh
Operation이 발생한 이후 즉시 (전체 인덱스가 아니라) shard를 refresh하기 위해서, 그리고 즉시 검색 결과에 operation이 적용된 document가 나타나게 하기 위해서는 refresh parameter를 true로 설정하면 된다. 이 옵션을 true로 설정하는 것은, indexing하는 것과 검색하는 양쪽 상황에서 성능상 문제를 일으키지 않는다는 주의 깊은 생각과 확신 속에서 수행되어야만 한다. Get API를 통해서 document를 조회하는 것은 realtime으로 이루어진다는 것을 유의하라.
Timeout
Index operation을 수행하도록 할당된 primary shard는 index operation이 실행되고 있을 때는 이용할 수 없다. 여기에는 몇 가지 이유가 있는데, primary shard는 gateway로부터 바로 기록되고 재배치가 일어나기 때문이다. 기본적으로 index operation은 primary shard를 사용할 수 있을 때까지 약 1분 정도를 기다린다. 1분 이후에는 실패로 간주하고 오류를 응답한다. Timeout parameter는 얼마나 오래 응답을 기다릴 것인지를 명시적으로 설정하는데 사용된다. 다음 예제에서는 5분으로 설정하고 있다.
$ curl -XPUT 'http://localhost:9200/twitter/tweet/1?timeout=5m' -d '{
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}'
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*, -* 처럼 설정할 수도 있다. (+는 허용, -는 불허를 의미한다.)