'API'에 해당되는 글 7건

  1. 2021.07.05 [Elasticsearch] Bulk Request by Restful API
  2. 2020.09.03 [Elasticsearch] API Key (중복)
  3. 2020.06.19 [Elasticsearch] X-pack Security API Key 사용 해 보기
  4. 2018.04.03 [Elasticsearch] JSON 스트링으로 질의요청
  5. 2017.07.17 [esquery-proxy] Elasticsearch 용 RESTful API Gateway/Proxy
  6. 2017.02.01 [Appboy] REST API 를 이용한 이벤트 처리
  7. 2015.07.02 [Elasticsearch] shard allocation 운영 테스트용 REST 코드

[Elasticsearch] Bulk Request by Restful API

Elastic/Elasticsearch 2021. 7. 5. 15:41

공홈 문서 보시면 됩니다.

https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html

 

워낙에 제가 예전에 작성해 놓은 글이 있어서 그냥 최신 버전으로 remind 합니다.

$ curl -s -H "Content-Type: application/x-ndjson" -XPOST http://localhost:9200/_bulk 
  --data-binary "@ATC.json"

 

ATC.json)

{"index": { "_index": "atc", "_id": "1"}}
{"chosung": "ㄴㅇㅋ", "chosung_eng": "nike", "jamo_kor": "ㄴㅏㅇㅣㅋㅣ", "jamo_eng": "skdlzl", "item_kor": "나이키", "item_eng": "nike"}

 

:

[Elasticsearch] API Key (중복)

Elastic/Elasticsearch 2020. 9. 3. 10:16

이전에 작성한 글과 중복 내용이 있습니다.

 

이전 글)

jjeong.tistory.com/1487

 

Elasticsearch + Kibana 사용 시 basic security 설정을 enable 하게 되면 Restful API 사용을 위한 API Key 를 생성 해서 사용을 해야 합니다.

 

Kibana devtools 를 이용해서 할 경우 인증이 되어 있어서 /_security/api_key 사용이 가능 하지만 Postman 과 같은 걸 이용할 경우 id:pwd 를 넣어 줘야 합니다.

[Case 1]
http://elastic:elasticpassword@localhost:9200/_security/api_key

[Case 2]
curl -XPUT -u elastic:elasticpassword "http://localhost:9200/_security/api_key" -d
{
  "name": "team-index-command",
  "expiration": "10m", 
  "role_descriptors": { 
    "role-team-index-command": {
      "cluster": ["all"],
      "index": [
        {
          "names": ["*"],
          "privileges": ["all"]
        }
      ]
    }
  }
}

 

API Key 구조)

- /_security/api_key 를 이용해서 생성을 하면 아래와 같은 값이 나옵니다.

[Request]
POST /_security/api_key
{
  "name": "team-index-command",
  "expiration": "10m", 
  "role_descriptors": { 
    "role-team-index-command": {
      "cluster": ["all"],
      "index": [
        {
          "names": ["*"],
          "privileges": ["all"]
        }
      ]
    }
  }
}

[Response]
{
  "id" : "87cuynIBjKAXtnkobGgo",
  "name" : "team-index-command",
  "expiration" : 1592529999478,
  "api_key" : "OlVGT_Q8RGq1C_ASHW7pGg"
}

- API Key 는 id:api_key 조합으로 base64 encoding 된 값입니다.

base64_encode("87cuynIBjKAXtnkobGgo"+":"+"OlVGT_Q8RGq1C_ASHW7pGg")

 

API Key 를 이용한 Restful API 호출)

$ curl 
  -H "Authorization: ApiKey VGVVOXluSUJHUUdMaHpvcUxDVWo6aUtfSmlEMmdSMy1FUUFpdENCYzF1QQ==" 
  http://localhost:9200/_cluster/health

 

:

[Elasticsearch] X-pack Security API Key 사용 해 보기

Elastic/Elasticsearch 2020. 6. 19. 11:07

Elastic Stack 이 좋은 이유는 기본 Basic license 까지 사용이 가능 하다는 것입니다.

사실 이것 말고도 엄청 많죠 ㅎㅎ 

 

https://www.elastic.co/subscriptions

 

딱 API keys management 까지 사용이 됩니다. ㅎㅎㅎ

 

먼저 사용하기에 앞서서 Elasticsearch 와 Kibana 에 x-pack 사용을 위한 설정을 하셔야 합니다.

 

[Elasticsearch]

- elasticsearch.yml

xpack.monitoring.enabled: true
xpack.ml.enabled: true
xpack.security.enabled: true

xpack.security.authc.api_key.enabled: true
xpack.security.authc.api_key.hashing.algorithm: "pbkdf2"
xpack.security.authc.api_key.cache.ttl: "1d"
xpack.security.authc.api_key.cache.max_keys: 10000
xpack.security.authc.api_key.cache.hash_algo: "ssha256"

위 설정은 기본이기 때문에 환경에 맞게 최적화 하셔야 합니다.

https://www.elastic.co/guide/en/elasticsearch/reference/7.8/security-settings.html#api-key-service-settings

 

[Kibana]

- kibana.yml

xpack:
  security:
    enabled: true
    encryptionKey: "9c42bff2e04f9b937966bda03e6b5828"
    session:
      idleTimeout: 600000
    audit:
      enabled: true

 

이렇게 설정 한 후 id/password 설정을 하시면 됩니다.

 

# bin/elasticsearch-setup-passwords interactive
Initiating the setup of passwords for reserved users elastic,apm_system,kibana,logstash_system,beats_system,remote_monitoring_user.
You will be prompted to enter passwords as the process progresses.
Please confirm that you would like to continue [y/N]y

Enter password for [elastic]:
Reenter password for [elastic]:
Enter password for [apm_system]:
Reenter password for [apm_system]:
Enter password for [kibana]:
Reenter password for [kibana]:
Enter password for [logstash_system]:
Reenter password for [logstash_system]:
Enter password for [beats_system]:
Reenter password for [beats_system]:
Enter password for [remote_monitoring_user]:
Reenter password for [remote_monitoring_user]:
Changed password for user [apm_system]
Changed password for user [kibana]
Changed password for user [logstash_system]
Changed password for user [beats_system]

Changed password for user [remote_monitoring_user]
Changed password for user [elastic]

 

이렇게 설정이 끝나면 kibana 에 접속해서 API key 를 생성 하시면 됩니다.

아래 문서는 생성 시 도움이 되는 문서 입니다.

 

www.elastic.co/guide/en/elasticsearch/reference/current/security-privileges.html

www.elastic.co/guide/en/elasticsearch/reference/7.7/security-api-put-role.htmlwww.elastic.co/guide/en/elasticsearch/reference/7.7/defining-roles.htmlwww.elastic.co/guide/en/elasticsearch/reference/7.7/security-api-create-api-key.html

 

Kibana Console 에서 아래와 같이 생성이 가능 합니다.

POST /_security/api_key
{
  "name": "team-index-command",
  "expiration": "10m", 
  "role_descriptors": { 
    "role-team-index-command": {
      "cluster": ["all"],
      "index": [
        {
          "names": ["*"],
          "privileges": ["all"]
        }
      ]
    }
  }
}

{
  "id" : "87cuynIBjKAXtnkobGgo",
  "name" : "team-index-command",
  "expiration" : 1592529999478,
  "api_key" : "OlVGT_Q8RGq1C_ASHW7pGg"
}

생성 이후 사용을 위해서는 

 

- ApiKey 는 id:api_key 를 base64 인코딩 합니다.

base64_encode("87cuynIBjKAXtnkobGgo"+":"+"OlVGT_Q8RGq1C_ASHW7pGg")
==> VGVVOXluSUJHUUdMaHpvcUxDVWo6aUtfSmlEMmdSMy1FUUFpdENCYzF1QQ==
curl -H 
  "Authorization: ApiKey VGVVOXluSUJHUUdMaHpvcUxDVWo6aUtfSmlEMmdSMy1FUUFpdENCYzF1QQ==" 
  http://localhost:9200/_cluster/health

이제 용도와 목적에 맞춰서 API key 를 만들고 사용 하시면 되겠습니다.

 

:

[Elasticsearch] JSON 스트링으로 질의요청

Elastic/Elasticsearch 2018. 4. 3. 13:41

예전에도 JSON 스트링을 가지고 setSource() 함수로 질의 했었는데요.

필요하신 분들이 계신것 같아 쉬운 샘플 코드 올려 봅니다.


[Source Code]

package org.elasticsearch.action.search;

import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class HelloSearchSourceBuilder {

public static void main (String[] args) {
Client client;
client = new PreBuiltTransportClient(Settings.EMPTY);

SearchRequestBuilder searchRequestBuilder = client.prepareSearch();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("field1","value1");

System.out.println(termQueryBuilder.toString());

searchSourceBuilder.query(termQueryBuilder).from(0).size(10);

System.out.println(searchSourceBuilder.toString());

searchRequestBuilder.setSource(searchSourceBuilder);

System.out.println(searchRequestBuilder.toString());
}
}


[Output]

[2018-04-03T13:36:38,466][INFO ][o.e.p.PluginsService     ] [_client_] no modules loaded

[2018-04-03T13:36:38,470][INFO ][o.e.p.PluginsService     ] [_client_] loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin]

[2018-04-03T13:36:38,470][INFO ][o.e.p.PluginsService     ] [_client_] loaded plugin [org.elasticsearch.join.ParentJoinPlugin]

[2018-04-03T13:36:38,470][INFO ][o.e.p.PluginsService     ] [_client_] loaded plugin [org.elasticsearch.percolator.PercolatorPlugin]

[2018-04-03T13:36:38,470][INFO ][o.e.p.PluginsService     ] [_client_] loaded plugin [org.elasticsearch.script.mustache.MustachePlugin]

[2018-04-03T13:36:38,470][INFO ][o.e.p.PluginsService     ] [_client_] loaded plugin [org.elasticsearch.transport.Netty4Plugin]

{

  "term" : {

    "field1" : {

      "value" : "value1",

      "boost" : 1.0

    }

  }

}

{"from":0,"size":10,"query":{"term":{"field1":{"value":"value1","boost":1.0}}}}

{"from":0,"size":10,"query":{"term":{"field1":{"value":"value1","boost":1.0}}}}


Process finished with exit code 0



:

[esquery-proxy] Elasticsearch 용 RESTful API Gateway/Proxy

ITWeb/검색일반 2017. 7. 17. 19:01

Elasticsearch 를 서비스 용도로 많은 분들이 사용하고 계시는 것으로 압니다.

저 처럼 Java API를 사용하고 계신 분들도 계실 테고 RESTful API 를 사용하고 계신 분들도 계실 것으로 압니다.

그냥 버전 업그레이도 해야 하고 해서 재미 삼아 가볍게 만들어 보았습니다.

관련해서 

- 단순 기능 동작 유무만 확인했습니다. (잘 됩니다.)

- 성능 테스트 하지 않았습니다.

- 안정성 테스트 하지 않았습니다.

그래서 가져다 막 고쳐서 사용하시면 좋겠습니다. 


일단 만들게 된 동기는

- Search 와 Aggregation 에 대해서 사용할 목적으로 만들었습니다.

- Elasticsearch JAVA API 버전 관리에 대한 유지보수 비용을 절감 해야 했습니다.

- Elasticsearch Cluster 에 대한 Version Upgrade 도 수행 해야 했습니다.

- Multi Cluster 에 대한 Concurrent 처리가 가능 해야 했습니다.


프로젝트 코드를 보시면 아시겠지만 매우 간단 합니다.


사용한 Framework)

- SpringMVC + Maven Project

- pom.xml  내 dependency 참고 하시면 됩니다.


지원 가능한 API)

- Elasticsearch에서 제공하는 거의 모든 RESTful API 를 제공 합니다.

- HTTP POST 만 구현해 놨기 때문에 POST 를 지원하지 않는 API 는 동작 하지 않습니다.

- 조만간 시간 나는데로 추가해 보겠습니다.

- Single Request 뿐만 아니라 Multi Request 도 지원 합니다.

- Single Cluster 뿐만 아니라 Multi Cluster 로 Request 를 보낼 수 있습니다.

-  서로 다른 Version 의 Cluster 라도 상관 없습니다.


Single Request Example)

[WAS Endpoint]

http://localhost:8080/query


[Method]

POST RAW


[Request Body]

{

  "target":"http://{YOUR-CLUSTER}/{YOUR-INDEX}/_search",

  "query":{}

}

- target

-  요청할 Elasticsearch Cluster 의 RESTful Endpoint 를 작성 하시면 됩니다.

- {YOUR-INDEX} 는 alias, single index, multi index  모두 사용 가능 합니다.

- query

- 기존에 사용하시던 QueryDSL 문을 그대로 넣어 주시면 됩니다.

- match_all  query 가 실행 됩니다.


Multi Request Example)

[WAS Endpoint]

http://localhost:8080/mquery


[Method]

POST RAW


[Request Body]

[

{

  "target":"http://{YOUR-CLUSTER1}/{YOUR-INDEX1}/_search",

  "query":{}

},

{

  "target":"http://{YOUR-CLUSTER1}/{YOUR-INDEX2}/_search",

  "query":{}

},

{

  "target":"http://{YOUR-CLUSTER2}/{YOUR-INDEX1}/_search",

  "query":{}

},

{

  "target":"http://{YOUR-CLUSTER2}/{YOUR-INDEX2}/_search",

  "query":{}

}

]


 Multi Request 의 경우 _msearch API 와 비슷 하게 동작은 합니다.

다만, _msearch의 경우 서로 다른 클러스터간에 통신은 지원 하지 않습니다.



추가 Parameters)

- routing

이 기능은 특정 key 를 가지고 문서를 저장 하기 위한 대상 shard 를 지정 하기 위해 사용 합니다.

문서 저장 시 해당 key 에 대한 Grouping 이나 Classify 를 위해 사용 합니다.

자세한 내용은 Elastic 사의 Reference 문서를 참고하세요. (클릭)

- preference

이 기능은 검색 질의 시 아주 유용하게 활용이 가능 합니다.

특정 shard 를 지정 할 수도 있고 질의 하고 싶은 node 를 선택 할 수도 있습니다.

자세한 내용은 Elastic 사의 Reference 문서를 참고하세요. (클릭)


Github Repository)

https://github.com/HowookJeong/esquery-proxy

:

[Appboy] REST API 를 이용한 이벤트 처리

ITWeb/개발일반 2017. 2. 1. 14:01

앱보이 API 를 이용해서 앱에서 이벤트 푸쉬를 발생 하기 위한 예제 코드 입니다.

네이티브 앱은 SDK 를 이용하면 되지만 웹뷰는 REST API 를 이용해야 합니다.


# endpoint

https://api.appboy.com/users/track

 

# method

POST

 

# header

Content-Type: application/json

 

# body raw

{

"app_group_id":"xxxxx-xxxxx-xxxx-xxxxx",

"events": [

    {

        "external_id":"xxxxx-xxxxxx-xxxxxxx-xxxxxx",

        "name":"$EVENT_NAME$",

        "properties": {

            "keyword":"$KEYWORD$"

        },

        "time":"2017-01-26T07:10:00+09:00"

    }

]

}


참고문서)

https://www.appboy.com/documentation/REST_API/

:

[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}'



: